Spring MethodInvokingFactoryBean的用法

作用

  1. 让某个实例的某个方法的返回值注入为Bean的实例
  2. 让某个类的静态方法的返回值注入为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的实例


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值