獲取其他Bean的屬性值:
PropertyPathFactoryBean用來獲取目標Bean的屬相值(實際上就是它的getter方法的返回值),獲得的值可以注入給其他Bean,也可以直接定義成新的Bean。
使用PropertyPathFactoryBean來調用其他Bean的getter方法需要指定如下信息:
- 調用哪個對象。有PropertyPathFactoryBean的setTargetPbject(Object targetObject)方法指定。
- 調用哪個getter方法。由PropertyPathFactoryBean的setPropertyPath(String propertyPath)方法指定。
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<!-- 定義一個將要被應用的目標Bean -->
<bean id="persion" class="entity.Persion">
<property name="age" value="30"/>
<property name="son">
<!-- 使用嵌套Bean定義setSon()方法的參數值 -->
<bean class="entity.Son">
<property name="age" value="11"/>
</bean>
</property>
</bean>
<!-- 將指定Bean實例的getter方法返回值定義成son1 Bean -->
<bean id="son1" class="entity.Son1">
<!--確定目標Bean,指定son1 Bean來自哪個Bean的getter方法 -->
<property name="targetBeanName" value="persion"/>
<!-- 指定son1 Bean來自目標Bean的那個getter方法,son代表getSon() -->
<property name="propettyPath" value="son"/>
</bean>
</beans>
SpringTest.java
public class SpringTest
{
public static void main(String[] args)
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
System.out.println("系統獲取son1:"ctx.getBean("son1"));
}
}
輸出
系統獲取son1: Son[age=11]
獲取Field值:
獲取方法返回值:
Spring框架的本質就是通過XML配置來執行java代碼,因此幾乎可以把所有的Java代碼放到Spring配置文件中管理:
- 調用構造器創建對象(包括使用工廠方法創建對象),用<bean.../>元素。
- 調用setter方法,用<property.../>元素。
- 調用getter方法,PropertyPathFactoryBean或<util:property-path.../>元素。
- 調用普通方法,用MethodInvokingFactoryBean工廠Bean。
- 獲取Field的值,用FieldRetrievingFactoryBean或<util:constant.../>元素。
一般來說,應該講如下兩類信息放到XML配置文件中管理:
- 項目升級、維護時經常需要改動的信息。
- 控制項目類各組件耦合關系的代碼。