作用
- 让某个实例的某个方法的返回值注入为Bean的实例
- 让某个类的静态方法的返回值注入为Bean的实例
使用MethodInvokingFactoryBean
spring-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--调用静态方法的返回值作为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"/>
<!-- 将实例方法返回值直接定义成Bean -->
<!-- 确定调用目标方法的参数 -->
<property name="arguments">
<!-- list元素列出调用方法多个参数值 -->
<list>
<value>java.version</value>
</list>
</property>
</bean>
</beans>
使用:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/resources/spring-beans.xml");
Properties pero = (Properties) context.getBean("sysProps");
String version = (String)context.getBean("javaVersion");
System.out.println(pero.getProperty("java.version"));
System.out.println(version);
}
结果:
信息: Loading XML bean definitions from class path resource [resources/spring-beans.xml]
1.8.0_144
1.8.0_144
Process finished with exit code 0
静态注入
<!-- 静态注入,相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
<property name="arguments">
<list>
<value>securityManager</value>
</list>
</property>
</bean>
指定一个staticMethod
,静态的set
方法,另外一个参数是目标对象。把这个对象赋值过去。如果arguments
是多个,采用 List 赋值。
参考文档: spring MethodInvokingFactoryBean 的使用和了解,Spring 通过通过方法创建Bean的实例