獲取其他Bean的屬性值:
PropertyPathFactoryBean用來(lái)獲取目標(biāo)Bean的屬相值(實(shí)際上就是它的getter方法的返回值),獲得的值可以注入給其他Bean,也可以直接定義成新的Bean。
使用PropertyPathFactoryBean來(lái)調(diào)用其他Bean的getter方法需要指定如下信息:
- 調(diào)用哪個(gè)對(duì)象。有PropertyPathFactoryBean的setTargetPbject(Object targetObject)方法指定。
- 調(diào)用哪個(gè)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" >
<!-- 定義一個(gè)將要被應(yīng)用的目標(biāo)Bean -->
<bean id="persion" class="entity.Persion">
<property name="age" value="30"/>
<property name="son">
<!-- 使用嵌套Bean定義setSon()方法的參數(shù)值 -->
<bean class="entity.Son">
<property name="age" value="11"/>
</bean>
</property>
</bean>
<!-- 將指定Bean實(shí)例的getter方法返回值定義成son1 Bean -->
<bean id="son1" class="entity.Son1">
<!--確定目標(biāo)Bean,指定son1 Bean來(lái)自哪個(gè)Bean的getter方法 -->
<property name="targetBeanName" value="persion"/>
<!-- 指定son1 Bean來(lái)自目標(biāo)Bean的那個(gè)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("系統(tǒng)獲取son1:"ctx.getBean("son1"));
}
}
輸出
系統(tǒng)獲取son1: Son[age=11]
獲取Field值:
獲取方法返回值:
Spring框架的本質(zhì)就是通過(guò)XML配置來(lái)執(zhí)行java代碼,因此幾乎可以把所有的Java代碼放到Spring配置文件中管理:
- 調(diào)用構(gòu)造器創(chuàng)建對(duì)象(包括使用工廠方法創(chuàng)建對(duì)象),用<bean.../>元素。
- 調(diào)用setter方法,用<property.../>元素。
- 調(diào)用getter方法,PropertyPathFactoryBean或<util:property-path.../>元素。
- 調(diào)用普通方法,用MethodInvokingFactoryBean工廠Bean。
- 獲取Field的值,用FieldRetrievingFactoryBean或<util:constant.../>元素。
一般來(lái)說(shuō),應(yīng)該講如下兩類信息放到XML配置文件中管理:
- 項(xiàng)目升級(jí)、維護(hù)時(shí)經(jīng)常需要改動(dòng)的信息。
- 控制項(xiàng)目類各組件耦合關(guān)系的代碼。