spring源码学习---replaced-method的使用

 2019-10-17 21:31  阅读(1105)
文章分类:Spring boot

作为开发人员,我觉得直接看例子更好:
1、bean配置文件

<?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-4.0.xsd" default-lazy-init="true">
        <description>bean配置</description>

        <bean id="myBean" class="com.zzr.web.test.MyBean">
            <replaced-method name="display" replacer="replacer"/>
        </bean>

        <bean id="replacer" class="com.zzr.web.test.MyBeanReplacer"/>
    </beans>

2、MyBean代码

package com.zzr.web.test;

    /** * Created by sjgtw-zzr on 2018/5/17. */
    public class MyBean {
        public void display(){
            System.out.println("我是原来的方法");
        }
    }

3、MyBeanReplacer的代码

package com.zzr.web.test;

    import org.springframework.beans.factory.support.MethodReplacer;

    import java.lang.reflect.Method;

    /** * Created by sjgtw-zzr on 2018/5/17. */
    public class MyBeanReplacer implements MethodReplacer{
        @Override
        public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
            System.out.println("我替换了原来的方法");
            return null;
        }
    }

4、测试代码

package com.zzr.web.test;

    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.core.io.ClassPathResource;

    /** * Created by sjgtw-zzr on 2018/5/17. */
    public class Main {
        public static void main(String[] args) {
            BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("bean.xml"));
            MyBean myBean = (MyBean) beanFactory.getBean("myBean");
            myBean.display();
        }
    }

5、输出结果

我替换了原来的方法

使用场景:动态替换原有的业务逻辑


来源:[]()

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> spring源码学习---replaced-method的使用

相关推荐