spring 的Filed注入和method注入

 spring提供的了filed的值注入和method的返回值注入。

filed值注入需要使用org.springframework.beans.factory.config.FieldRetrievingFactoryBean。在配置文件中需要设置该类。然后再配置其需要注入的类的filed.例如

<beans>
  
<bean id="son" class="Bean.superIOCfield.Son">
     
<property name="age">
       
<bean id="Bean.superIOCfield.Field.TEST_FIELD" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"></bean>
     
</property>
  
</bean>
</beans>

其结果就是将Bean.superIOCfield.Field.TEST_FIELD的值注入给了age.

也可以通过配置targetObject和targetMethod属性来实现上面的配置,如果是静态的Filed则配置targetClasstargetMethod或者如下配置:

<bean id="max-long" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">

<property name="staticField">

<value>java.lang.Long.MAX_VALUE</value>

</property>

</bean>

Method返回值注入需要依赖注入MethodInvokingFactoryBean需要在xml中设定targetObjecttargetMethod来指定目标bean和方法如果使用静态方法,则需要指定targetClasstargetMethod

配置文件如下:

<bean id="bdog" class="com.spring.bible.ch3.Dog">

<property name="age">

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">

<property name="targetObject">

<ref local="randomAge"/>

</property>

<property name="targetMethod">

<value>getAge</value>

</property>

</bean>

</property>

</bean>

 

静态时:

<bean id="bdog" class="com.spring.bible.ch3.Dog">

<property name="age">

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">

<property name="targetClass">

<value>com.spring.bible.ch3.RandomAge</value>

</property>

<property name="targetMethod">

<!-- getAge必须是静态方法 -->

<value>getAges</value>

</property>

</bean>

</property>

</bean>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值