通过MethodInvokingFactoryBean工厂Bean,可以将指定方法返回值注入成为目标Bean的属性值,MethodInvokingFactoryBean用来获得指定方法的返回值,该方法可以是静态方法
也可以是实例方法。
获得的方法返回值既可以被注入到指定Bean实例的指定属性,也可以直接定义成Bean实例。
可以注入到静态方法:如:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>
也可以是普通方法
举例:
<?xml version="1.0" encoding="GBK"?>
<!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 -->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 定义目标Bean,后面将会获取该Bean的方法返回值 -->
<bean id="valueGenerator" class="com.b510.app.util.ValueGenerator"></bean>
<!-- 定义dog1的bean -->
<bean id="dog1" class="com.b510.service.impl.DogServiceBean">
<property name="age">
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<!-- targetObject确定目标Bean,指定调用哪个Bean -->
<property name="targetObject" ref="valueGenerator" />
<!-- targetMethod确定目标方法,指定调用目标Bean的哪个方法 -->
<property name="targetMethod" value="getAgeValue" />
</bean>
</property>
</bean>
<!-- 定义名为dog2的Bean -->
<bean id="dog2" class="com.b510.service.impl.DogServiceBean">
<property name="age">
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<!-- targetClass确定目标类,指定调用哪个类 -->
<property name="targetClass" value="com.b510.app.util.ValueGenerator" />
<!-- targetMethod确定目标方法,指定调用目标class的哪个方法。
该方法必须是静态方法-->
<property name="targetMethod" value="getAgeStaticValue"></property>
</bean>
</property>
</bean>
<!-- 将静态方法返回值直接定义成Bean -->
<bean id="sysProps"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<!-- targetClass确定目标类,确定调用哪个类 -->
<property name="targetClass" value="java.lang.System" />
<!-- targetMethod确定目标方法,确定调用目标class的哪个方法
该方法必须是静态方法-->
<property name="targetMethod" value="getProperties" />
</bean>
<!-- 将实例方法返回值直接定义成Bean -->
<bean id="javaVersion"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<!-- targetObject确定目标Bean,确定调用哪个Bean -->
<property name="targetObject" ref="sysProps" />
<!-- targetMethod确定目标方法,确定调用目标Bean的哪个方法 -->
<property name="targetMethod" value="getProperty" />
<!-- 确定调用目标方法的参数 -->
<property name="arguments">
<!-- list元素列出调用方法多个参数值 -->
<list>
<value>java.version</value>
</list>
</property>
</bean>
</beans>