FieldRetrievingFactoryBean 和 MethodInvokingFactoryBean
spring提供了filed的值注入和method的返回值注入。
1、Field值的注入
filed值注入需要使用org.springframework.beans.factory.config.FieldRetrievingFactoryBean来获取类的静态变量。
例如,我们通常在接口中定义常量:
view plaincopy to clipboardprint?package com.baobaotao.fb;
public interface CarBrandType {
String HONG_QI = "红旗";
String JI_LI = "吉利";
}
package com.baobaotao.fb;
public interface CarBrandType {
String HONG_QI = "红旗";
String JI_LI = "吉利";
}
下面利用FieldRetrievingFactoryBean获取CarBandType接口中定义的常量,并注入到某个bean的属性中:
view plaincopy to clipboardprint?<bean id="car" ref="hongQi"/>
</bean>
<bean id="hongQi"
<property name="staticField" value="com.baobaotao.fb.CarBrandType.HONG_QI"/>
</bean>
<bean id="car" ref="hongQi"/>
</bean>
<bean id="hongQi" value="com.baobaotao.fb.CarBrandType.HONG_QI"/>
</bean>
Spring还允许用户用常量的全限定名作为FieldRetrievingFactoryBean的id,其效果和通过配置staticField属性是一样的:
view plaincopy to clipboardprint?<bean id="car" ref="com.baobaotao.fb.CarBrandType.HONG_QI"/>
</bean>
<bean id="com.baobaotao.fb.CarBrandType.HONG_QI" />
<bean id="car" ref="com.baobaotao.fb.CarBrandType.HONG_QI"/>
</bean>
<bean id="com.baobaotao.fb.CarBrandType.HONG_QI" />
当然,也可以直接将FieldRetrievingFactoryBean以内置bean的方式对brand属性进行赋值,这样在配置上更紧凑一些:
view plaincopy to clipboardprint?<bean id="car" />
<bean id="bdog" />
对于静态方法:
view plaincopy to clipboardprint?<bean id="bdog" class="com.baobaotao.fb.Dog">
<property name="age">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass">
<value>com.baobaotao.fb.RandomAge</value>
</property>
<property name="targetMethod">
<!-- getAge必须是静态方法 -->
<value>getAges</value>
</property>
</bean>
</property>
</bean>