美文网首页
spring bean中子元素lookup-method和rep

spring bean中子元素lookup-method和rep

作者: 小陈阿飞 | 来源:发表于2018-11-22 17:01 被阅读1次

    1、lookup-method注入

    lookup method注入是spring动态改变bean里方法的实现。方法执行返回的对象,使用spring内原有的这类对象替换,通过改变方法返回值来动态改变方法。内部实现为使用cglib方法,重新生成子类,重写配置的方法和返回对象,达到动态改变的效果。

    package fiona.apple;
    
    // no more Spring imports!
    
    public abstract class CommandManager {
    
       public Object process(Object commandState) {
           // grab a new instance of the appropriate Command interface
           Command command = createCommand();
           // set the state on the (hopefully brand new) Command instance
           command.setState(commandState);
           return command.execute();
       }
    
       // okay... but where is the implementation of this method?
       protected abstract Command createCommand();
    }
    
    <bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
    </bean>
    
    <bean id="commandManager" class="fiona.apple.CommandManager">
     <lookup-method name="createCommand" bean="command"/>
    </bean>
    

    注意:由于采用cglib生成之类的方式,所以需要用来动态注入的类,不能是final修饰的;需要动态注入的方法,也不能是final修饰的。

    同时,还得注意command的scope的配置,如果scope配置为singleton,则每次调用方法createCommand,返回的对象都是相同的;如果scope配置为prototype,则每次调用,返回都不同。

    2、replaced-method注入

    replaced method注入是spring动态改变bean里方法的实现。需要改变的方法,使用spring内原有其他类(需要继承接口org.springframework.beans.factory.support.MethodReplacer)的逻辑,替换这个方法。通过改变方法执行逻辑来动态改变方法。内部实现为使用cglib方法,重新生成子类,重写配置的方法和返回对象,达到动态改变的效果。

    public class MyValueCalculator {
     
        public String computeValue(String input) {
            // some real code...
        }
     
        // some other methods...
     
    }
     
    /**
     * 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 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"/>
    

    注意:由于采用cglib生成之类的方式,所以需要用来动态注入的类,不能是final修饰的;需要动态注入的方法,也不能是final修饰的。

    相关文章

      网友评论

          本文标题:spring bean中子元素lookup-method和rep

          本文链接:https://www.haomeiwen.com/subject/uwalqqtx.html