天天看點

spring應用手冊-IOC(XML配置實作)-(23)-replaced-method标簽

戴着假發的程式員 出品

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方法的重載的情況。