spring应用手册-IOC(XML配置实现)-(23)-replaced-method标签

    科技2022-07-13  152

    戴着假发的程序员 出品

    replaced-method标签

    spring应用手册(第一部分)

    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.dk.demo2.service.AccountService$$EnhancerBySpringCGLIB$$f5322a5a@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>

    String可以配置任意多个。 这种情况往往用于AccountService有多个save方法的重载的情况。

    Processed: 0.011, SQL: 8