Spring MethodInvokingFactoryBean

2019-12-20  本文已影响0人  slowwalkerlcr

作用

使用MethodInvokingFactoryBean

<?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">
        <property name="targetClass" value="java.lang.System"/>
        <property name="targetMethod" value="getProperties"/>
    </bean>

    <!--调用实例方法的返回值作为bean-->
    <bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="sysProps"/>
        <property name="targetMethod" value="getProperty"/>
        <property name="arguments" value="java.version"/>
    </bean>
</beans>

2、下面是System中的静态方法的返回值Properties包含配置的属性的文件的信息,相当于调用静态方法然后在调用生成的Properties这个Bean的实例的方法的某个属性

  public static Properties getProperties() {
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPropertiesAccess();
        }

        return props;
    }

3、测试

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
        "classpath:spring-methodInvoking.xml"})
public class MethodTest extends AbstractJUnit4SpringContextTests{


    @Resource(name = "sysProps")
    public Properties properties;

    @Resource(name ="javaVersion")
    public String javaVersion;

    @Test
    public void test(){
        log.info(properties.toString());
        log.info(javaVersion.toString());
    }
}

测试总结

测试结果如同我们想象的一样,可以将某个方法或者某个具体的类的静态方法进行调用
因为我们总会调用这个方法,相当于初始化方法呗,对于返回值,你可以随便返回一个Boolean 这个就将这个Boolean的值注入到了
spring的容器中去了,不过这个不是最好的手段,你可以继承InitializingBean,或者使用注解@PostConstruct,在初始化Bean之前调用这个方法
但是有些时候不想初始化某个Bean你还是可以这么干的。

会使用开发中很重要,知其所以然也是很重要(了解这个背后实现的故事)

<bean id="testBean" class="org.springframework.beans.factory.config.MethodInvokingBean">
        <property name="staticMethod" value="com.common.utils.test.MethodInvokingBeanTest.test"></property>
    </bean>
@Slf4j
public class MethodInvokingBeanTest {
    public static void test(){
        log.info("调用了这个方法");
    }
}
 @Resource(name = "testBean")
    public MethodInvokingBean methodInvokingBean;
    @Test
    public void testMethod(){
        log.info(methodInvokingBean.getTargetMethod());
    }

INFO [MethodInvokingBeanTest.java:15] : 调用了这个方法
INFO [MethodTest.java:34] : test

参考链接 https://blog.csdn.net/u012881904/article/details/77531689

上一篇 下一篇

猜你喜欢

热点阅读