A less commonly useful form of method injection than Lookup method injection are the ability to replace arbitrary methods I n a managed bean with another method implementation. Users may safely skip the rest of this section (which describes this somewhat advanced feature), until this functionality is actually needed.
In an xmlbeanfactory, the replaced-method element is used to replace the existing method implementation with a Nother, for a deployed bean. Consider the following class, with a method computevalue, which we want to override:
... public class Myvaluecalculator {public String computevalue (String input) { ... some real code } ... s ome Other Methods}
A class implementing the Org.springframework.beans.factory.support.MethodReplacer interface is needed to Provide the new method definition.
/** meant to being used to override the existing Computevalue implementation in Myvaluecalculator */public class Replacem Entcomputevalue implements Methodreplacer {public object Reimplement (Object o, Method m, object[] args) throws Throwa ble { //Get the input value, work with it, and return a computed result String input = (String) args[0]; ... return ...;}
The Beanfactory deployment definition to deploy the original class and specify the method override would look like:
<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 "></bean>
One or more contained Arg-type elements within the Replaced-method element is used to indicate the M Ethod signature of the method being overridden. Note that the signature for the arguments are actually only needed in the case that the method is actually overloaded and T Here is multiple variants within the class. For convenience, the type string is a argument may be a substring of the fully qualified type name. For example, all the following would match java.lang.String.
Java.lang.String String Str
Since the number of arguments is often enough to distinguish between each possible choice, this shortcut can save a lot of Typing, by just using the shortest string which would match an argument.
3.3.5. Usingdepends-on
Spring's forced modification of a method's behavior (arbitrary method replacement)