戴着假发的程序员出品
[查看视频教程 https://www.bilibili.com/video/BV1RK411V7jF/?p=24 ]
replaced-method 可以让我们通过配置完成对原有的 bean 中的方法实现进行重新替换.
看案例:
我们有一个 service 类, 其中有一个 save 方法的实现
- /**
- * @author 戴着假发的程序员
- *
- * @description
- */
- public class AccountService {
- public void save(String name){
- System.out.println("AccountService-save:"+name);
- }
- }
我们制定一个替换实现类, 这个类必须试下你接口: org.springframework.beans.factory.support.MethodReplacer
- /**
- * @author 戴着假发的程序员
- *
- * @description
- */
- public class ReplacementSaveAccount implements MethodReplacer {
- /**
- * @param o 产生的代理对象
- * @param method 替换的方法对象
- * @param objects 提花的方法传入的参数
- * @return
- * @throws Throwable
- */
- @Override
- public Object reimplement(Object o, Method method, Object[] objects) throws Throwable {
- Object result = null;
- System.out.println("当前对象 o:"+o);
- System.out.println("原来的方法 method:"+method);
- for (Object arg : objects){
- System.out.println("参数 --:"+arg);
- }
- System.out.println("保存账户替换后的方法");
- return result;
- }
- }
配置如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans default-autowire="byName" 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 ReplacementSaveAccount -->
- <bean id="replacementSaveAccount" class="com.boxuewa.dk.demo2.service.ReplacementSaveAccount"/>
- <!-- accountService -->
- <bean id="accountService" class="com.boxuewa.dk.demo2.service.AccountService">
- <!-- 配置替换方法 -->
- <replaced-method name="save" replacer="replacementSaveAccount">
- <arg-type>String</arg-type>
- </replaced-method>
- </bean>
- </beans>
测试:
- @Test
- public void testReplaceMethod(){
- ApplicationContext ac =
- new ClassPathXmlApplicationContext("applicationContext-demo5.xml");
- AccountService bean = ac.getBean(AccountService.class);
- bean.save("戴着假发的程序员");
- }
结果:
当前对象 o:com.boxuewa.d[email protected]17776a8
原来的方法 method:public void com.boxuewa.dk.demo2.service.AccountService.save(java.lang.String)
参数 --: 戴着假发的程序员
保存账户替换后的方法
我们会发现 spring 会为我们生成一个 AccountService 的代理对象, 并且将其 save 方法的实现修改为我们制定的 ReplacementSaveAccount 中的 reimplement 实现.
注意: 下面配置中:
- <!-- 配置替换方法 -->
- <replaced-method name="save" replacer="replacementSaveAccount">
- <arg-type>String</arg-type>
- </replaced-method>
- <arg-type>String</arg-type > 可以配置任意多个. 这种情况往往用于 AccountService 有多个 save 方法的重载的情况.
来源: http://www.bubuko.com/infodetail-3680248.html