【Spring】 - lookup-method和replaced-method使用

xiaoxiao2021-02-28  95

概述

lookup-method和replaced-method是在xml配置bean的时候的可选配置,其中lookup-method可以声明方法返回某个特定的bean,replaced-method可以改变某个方法甚至是改变方法的逻辑。

使用

(略过环境配置) 定义一个User接口,和接口的两个实现Teacher和Student User接口: public interface User { public void showMe(); } Teacher类: public class Teacher implements User { @Override public void showMe() { System.out.println("I am a Teacher"); } } Student类: public class Student implements User { @Override public void showMe() { System.out.println("I am a Student"); } } 测试用的Bean: public abstract class MyTestBean { //用于测试lookup-method public abstract User getUserBean(); //用于测试replace-method public void changedMethod() { System.out.println("Origin method in MyTestBean run"); } } 这里的getUserBean返回一个User的实例。用于测试lookup-method 为了同时测试replace-method 这里定义一个 Replacer类: public class Replacer implements MethodReplacer { @Override public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { System.out.println("replacer method run"); return null; } }Replacer类需要实现MethodReplacer接口,该接口包含一个reimplement方法,这个方法最后将会代替被替代的方法来执行,同时参数中提供了相应的Object和Method以及参数等,明显允许我们利用反射的方式调用原来的方法。 接下来就是最关键的: xml配置 <bean id="myTestBean" class="io.spring.test.MyTestBean" > <lookup-method name="getUserBean" bean="student"/> <replaced-method name="changedMethod" replacer="replacer"/> </bean> <bean id="teacher" class="io.spring.test.Teacher" /> <bean id="student" class="io.spring.test.Student" /> <bean id="replacer" class="io.spring.test.Replacer" /> 将lookup-method和replaced-method的name指定为对应的方法名称。 编写测试类: public class MyBeanTest { @Test public void testMyBean() { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); MyTestBean bean = (MyTestBean) context.getBean("myTestBean"); bean.getUserBean().showMe(); bean.changedMethod(); } }执行后输出: I am a Student replacer method run 可以看到这里的lookup-method成功返回了Student的实例。同时changedMethod方法也被Replacer中的方法替代。 修改getUserBean的返回实例为Teacher xml配置: <bean id="myTestBean" class="io.spring.test.MyTestBean" > <lookup-method name="getUserBean" bean="teacher"/> <replaced-method name="changedMethod" replacer="replacer"/> </bean> <bean id="teacher" class="io.spring.test.Teacher" /> <bean id="student" class="io.spring.test.Student" /> <bean id="replacer" class="io.spring.test.Replacer" /> 同时修改一下 Replacer中的逻辑: public class Replacer implements MethodReplacer { @Override public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { System.out.println("replacer method run"); return method.invoke(obj.getClass().newInstance(), args); } } 再次运行测试用例: 输出: I am a Teacher replacer method run Origin method in MyTestBean run 以上便是lookup-method和replaced-method的使用方法。但是一般 不是很常用,比如lookup-method通常用@Autowired自动注入的时候就已经满足大部分使用场景了。
转载请注明原文地址: https://www.6miu.com/read-72846.html

最新回复(0)