JSP開(kāi)發(fā)之Spring方法注入之替換方法實(shí)現(xiàn)
Spring提供了一種替換方法實(shí)現(xiàn)的機(jī)制,可以讓我們改變某個(gè)bean某方法的實(shí)現(xiàn)。打個(gè)比方我們有一個(gè)bean,其中擁有一個(gè)add()方法可以用來(lái)計(jì)算兩個(gè)整數(shù)的和,但這個(gè)時(shí)候我們想把它的實(shí)現(xiàn)邏輯改為如果兩個(gè)整數(shù)的值相同則把它們相乘,否則還是把它們相加,在不改變或者是不能改變?cè)创a的情況下我們就可以通過(guò)Spring提供的替換方法實(shí)現(xiàn)機(jī)制來(lái)實(shí)現(xiàn)這一要求。
替換方法實(shí)現(xiàn)機(jī)制的核心是MethodReplacer接口,其中定義了一個(gè)reimplement ()方法,我們的替換方法實(shí)現(xiàn)的主要邏輯就是在該方法中實(shí)現(xiàn)的,
具體定義如下:
public interface MethodReplacer {
/**
* Reimplement the given method.
* @param obj the instance we're reimplementing the method for
* @param method the method to reimplement
* @param args arguments to the method
* @return return value for the method
*/
Object reimplement(Object obj, Method method, Object[] args) throws Throwable;
}
我們可以看到reimplement()方法將接收三個(gè)參數(shù),其中obj表示需要替換方法實(shí)現(xiàn)的bean對(duì)象,method需要替換的方法,args則表示對(duì)應(yīng)的方法參數(shù)。針對(duì)前面打的比方,假設(shè)我們有如下這樣一個(gè)類定義對(duì)應(yīng)的bean。
public class BeanA {
public int add(int a, int b) {
return a+b;
}
}
bean id="beanA" class="com.app.BeanA"/>
如果我們需要替換add()方法的實(shí)現(xiàn)為a與b相等時(shí)則相乘,否則就相加,則我們可以針對(duì)該方法提供一個(gè)對(duì)應(yīng)的MethodReplacer的實(shí)現(xiàn)類,具體實(shí)現(xiàn)如下所示。
public class BeanAReplacer implements MethodReplacer {
/**
* @param obj 對(duì)應(yīng)目標(biāo)對(duì)象,即beanA
* @param method 對(duì)應(yīng)目標(biāo)方法,即add
* @param args 對(duì)應(yīng)目標(biāo)參數(shù),即a和b
*/
public Object reimplement(Object obj, Method method, Object[] args)
throws Throwable {
Integer a = (Integer)args[0];
Integer b = (Integer)args[1];
if (a.equals(b)) {
return a * b;
} else {
return a + b;
}
}
}
之后就需要在定義beanA時(shí)指定使用BeanAReplacer來(lái)替換beanA的add()方法實(shí)現(xiàn),這是通過(guò)replaced-method元素來(lái)指定的。其需要指定兩個(gè)屬性,name和replacer。name用來(lái)指定需要替換的方法的名稱,而replacer則用來(lái)指定用來(lái)替換的MethodReplacer對(duì)應(yīng)的bean。所以,此時(shí)我們的beanA應(yīng)該如下定義:
bean id="beanAReplacer" class="com.app.BeanAReplacer"/>
bean id="beanA" class="com.app.BeanA">
replaced-method name="add" replacer="beanAReplacer"/>
/bean>
如果我們的MethodReplacer將要替換的方法在對(duì)應(yīng)的bean中屬于重載類型的方法,即存在多個(gè)方法名相同的方法時(shí),我們還需要通過(guò)在replaced-method元素下通過(guò)arg-type元素來(lái)定義對(duì)應(yīng)方法參數(shù)的類型,這樣就可以區(qū)分需要替換的是哪一個(gè)方法。所以,針對(duì)上述示例,我們也可以如下定義:
bean id="beanAReplacer" class="com.app.BeanAReplacer"/>
bean id="beanA" class="com.app.BeanA">
replaced-method name="add" replacer="beanAReplacer">
arg-type match="int"/>
arg-type match="int"/>
/replaced-method>
/bean>
對(duì)應(yīng)方法名的方法只存在一個(gè)時(shí),arg-type將不起作用,即Spring此時(shí)不會(huì)根據(jù)arg-type去取對(duì)應(yīng)的方法進(jìn)行替換,或者換句話說(shuō)就是當(dāng)replaced-method指定名稱的方法只存在一個(gè)時(shí),無(wú)論arg-type如何定義都是可以的。
以上就是JSP中Spring方法注入之替換方法實(shí)現(xiàn)的實(shí)例,希望能幫助到大家,如有疑問(wèn)可以留言討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!