在Spring Io容器里,用户可以是用某个Bean的方法去替换另一个Bean的方法。
在下面例子中,Boss1的getCar()方法,返回一辆宝马车z4;
package com.lxm.injectfun;
public class Boss1{
public Car getCar(){
Car car=new Car();
car.setBrand("宝马z4")
return car;
}
}
在Boss2实现了Spring的org.springframework.beans.factory.support.MethodReplacer接口jiekizai接口方法reimpliment(),返回一辆美人豹:
package com.lxm.injectfun;
import java.lang.reflect,Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class Boss2 implements MethodReplacer{
public Object reimplenent(Object arg0,Method arg1,Object[] arg2)
throws Throwable{
Car car=new CAR();
car.setBrand("美人豹“);
return car;
}
}
用于替换他人的Bean 必须实现MethokReplacer接口,Spring 将利用该接口方法去替换目标Bean 的方法。下面,我们通过Spring IoC容器的“乾坤大挪移”术,用Boss2的方法替换Boss1的getCar():
<bean id="boss1" class="com.lxm.injiectfun.Boss1>
<replaced-method name="getCar" replacer="boss2"/>
</bean>
<bean id="boss2 class="com.lxm.injiectfun.Boss2"/>
当从容器中返回boss1 Bean并调用其getCar()方法时,将返回一辆“美人豹”的Car,调用成功。