戴着假发的程序员出品
[查看视频教程]
replaced-method可以让我们通过配置完成对原有的bean中的方法实现进行重新替换。
看案例:
我们有一个service类,其中有一个save方法的实现
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 public class AccountService { 7 public void save(String name){ 8 System.out.println("AccountService-save:"+name); 9 } 10 }
我们制定一个替换实现类,这个类必须试下你接口:org.springframework.beans.factory.support.MethodReplacer
1 /** 2 * @author 戴着假发的程序员 3 * 4 * @description 5 */ 6 public class ReplacementSaveAccount implements MethodReplacer { 7 /** 8 * @param o 产生的代理对象 9 * @param method 替换的方法对象 10 * @param objects 提花的方法传入的参数 11 * @return 12 * @throws Throwable 13 */ 14 @Override 15 public Object reimplement(Object o, Method method, Object[] objects) throws Throwable { 16 Object result = null; 17 System.out.println("当前对象o:"+o); 18 System.out.println("原来的方法method:"+method); 19 for (Object arg : objects){ 20 System.out.println("参数--:"+arg); 21 } 22 System.out.println("保存账户替换后的方法"); 23 return result; 24 } 25 }
配置如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans default-autowire="byName" xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 <!-- 替换Bean ReplacementSaveAccount --> 7 <bean id="replacementSaveAccount" class="com.boxuewa.dk.demo2.service.ReplacementSaveAccount"/> 8 <!-- accountService --> 9 <bean id="accountService" class="com.boxuewa.dk.demo2.service.AccountService"> 10 <!-- 配置替换方法 --> 11 <replaced-method name="save" replacer="replacementSaveAccount"> 12 <arg-type>String</arg-type> 13 </replaced-method> 14 </bean> 15 </beans>
测试:
@Test public void testReplaceMethod(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-demo5.xml"); AccountService bean = ac.getBean(AccountService.class); bean.save("戴着假发的程序员"); }
结果:
1 当前对象o:com.boxuewa.dk.demo2.service.AccountService$$EnhancerBySpringCGLIB$$f5322a5a@17776a8 2 原来的方法method:public void com.boxuewa.dk.demo2.service.AccountService.save(java.lang.String) 3 参数--:戴着假发的程序员 4 保存账户替换后的方法
我们会发现spring会为我们生成一个AccountService的代理对象,并且将其save方法的实现修改为我们制定的ReplacementSaveAccount中的reimplement实现。
注意:下面配置中:
1 <!-- 配置替换方法 --> 2 <replaced-method name="save" replacer="replacementSaveAccount"> 3 <arg-type>String</arg-type> 4 </replaced-method>
原文:https://www.cnblogs.com/jiafa/p/13769365.html