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

作为开发人员,我觉得直接看例子更好:
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、输出结果

我替换了原来的方法

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

    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/zhaozhirongfree1111/article/details/80394376
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞