1. 引用其他Bean的属性值
PropertyPathFactoryBean & FieldRetrievingFactoryBean可以用来获得目标Bean的属性值(实际上就是调用getter方法返回的值),获得的值可以注入给其他的Bean,配置如下:
<bean id="person2" class="com.springframework.chapter35.Person">
<property name="name" value="ouyp" />
<property name="city">
<bean class="com.springframework.chapter35.City">
<property name="code">
<bean id="person.city.code" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"></bean>
</property>
</bean>
</property>
<property name="value">
<bean class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField" value="java.sql.Connection.TRANSACTION_SERIALIZABLE" />
</bean>
</property>
</bean>
这个其实还可以使用SpringEL来解决,看配置:
<bean id="person5" class="com.springframework.chapter35.Person">
<property name="name" value="ouyp" />
<property name="city">
<bean class="com.springframework.chapter35.City">
<property name="code" value="#{person.city.code}" />
</bean>
</property>
</bean>
对于使用org.springframework.beans.factory.config.PropertyPathFactoryBean和SpringEL,可以发现使用SpringEL更加简单便捷.
2.引用其他Bean方法的返回值
通过org.springframework.beans.factory.config.MethodInvokingFactoryBean可将目标方法的返回值注入为Bean的属性值。该方法既可以是静态方法,也可以是实例方法;这个值既可以被注入到指定Bean实例的指定属性,也可以直接定义成Bean实例。配置如下:
<bean id="person3" class="com.springframework.chapter35.Person">
<property name="name" value="kk" />
<property name="city">
<bean class="com.springframework.chapter35.City">
<property name="code">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="person" />
<property name="targetMethod" value="getName" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="person4" class="com.springframework.chapter35.Person">
<property name="name" value="kk" />
<property name="city">
<bean class="com.springframework.chapter35.City">
<property name="code">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="java.lang.System.getProperty" />
<property name="arguments">
<list>
<value>java.version</value>
</list>
</property>
</bean>
</property>
</bean>
</property>
</bean>
MethodInvokingFactoryBean在引用方法的时候由于存在重载的情况,可以传入参数来做区分。