spring的replaced-method分析

1:分析

实现动态替换某bean的某个方法的效果,可以实现无需修改代码,改变执行逻辑的功能。

2:实例

2.1:定义被替换方法的类

public class ReplacedMethodCls {
    
    
    public void sayHi() {
    
    
        System.out.println("hi from old method");
    }
}

2.2:定义替换的类

需要实现org.springframework.beans.factory.support.MethodReplacer接口,该接口源码如下:

public interface MethodReplacer {
    
    
	Object reimplement(Object obj, Method method, Object[] args) throws Throwable;
}

唯一的方法reimplement就是要执行的新方法,在这里编写新逻辑即可。参数说明:

obj:通过cjlib动态生成的被替换方法所在bean的子类。
method:被替换的方法对象。
args:执行方法需要的参数。
public class MyReplacedMethod implements MethodReplacer {
    
    
    @Override
    public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
    
    
        System.out.println("hi from new method");
        return null;
    }
}

2.3:配置文件

<?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">
    <!-- 定义method replacer -->
    <bean id="myReplacedMethod" class="yudaosourcecode.replacedmethod.MyReplacedMethod"/>

    <!-- 定义被替换方法的bean -->
    <bean id="replacedMethodCls" class="yudaosourcecode.replacedmethod.ReplacedMethodCls">
        <!--
        name:被替换的方法
        replacedMethodCls:替换方法所在类的bean名称,即实现了MethodReplacer接口的类
        -->
        <replaced-method name="sayHi" replacer="myReplacedMethod"/>
    </bean>
</beans>

2.4:测试代码

@Test
public void testReplacedMethod() {
    
    
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:testreplacedmethod.xml");
    ReplacedMethodCls replacedMethodCls = ac.getBean("replacedMethodCls", ReplacedMethodCls.class);
    replacedMethodCls.sayHi();
}

运行:

hi from new method

Process finished with exit code 0

<replaced-method name="sayHi" replacer="myReplacedMethod"/>注释掉,在运行,可以看到不会再替换,而是调用原始方法了:

hi from old method

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/wang0907/article/details/114325252