总结spring替代方法的使用
MyValueCalculator类中的computerValue方法将会被替代
public class MyValueCalculator { public String computeValue(String input) { // some real code... } // some other methods... }
替代类实现接口MethodReplacer
/** * meant to be used to override the existing computeValue(String) * implementation in MyValueCalculator */ public class ReplacementComputeValue implements MethodReplacer { public Object reimplement(Object o, Method m, Object[] args) throws Throwable { // get the input value, work with it, and return a computed result String input = (String) args[0]; ... return ...; } }
bean配置
<bean id="myValueCalculator" class="x.y.z.MyValueCalculator">
<!-- arbitrary method replacement -->
<replaced-method name="computeValue" replacer="replacementComputeValue">
<arg-type>String</arg-type>
</replaced-method>
</bean>
<bean id="replacementComputeValue" class="a.b.c.ReplacementComputeValue"/>
总结:这样就可以将computeValue方法交给类ReplacementComputeValue来完成。这是一种动态代理模式。由此想到了mybatis通过使用动态代理将自定义的dao接口的实现通过代理方法实现。