Lookup 方法注入和任意方法替换

来源:互联网 发布:手机壁纸主题软件 编辑:程序博客网 时间:2024/05/17 04:53

Lookup method injection(Lookup 方法注入)


简单例子说明,

    类person是一个抽象类,方法Msg返回一个字符串,(其实这里可以设计的好点返回一类实例)
    在sayMsg中输出返回的字符串
    
    abstract public class Person {                        public void sayMsg(){                        String msg = getMsg();            System.out.println(msg);        }                abstract public String getMsg();    }



    配置文件信息,通过lookup-method节点配置了抽象方法返回对象
       
        <bean id="msg" class="java.lang.String">            <constructor-arg type="java.lang.String" value="大家上午好"></constructor-arg>        </bean>                <bean id="person" class="com.link2.Person">            <lookup-method name="getMsg" bean="msg"/>        </bean>


        


    public class Maiin {                public static void main(String[] args) {            ApplicationContext ctx = new ClassPathXmlApplicationContext("hello.xml");                        Person bean = (Person) ctx.getBean("person");            bean.sayMsg();//控制台输出大家上午好        }    }



    在这里spring将会利用CGLIB动态的生成一个抽象类的子类并实现方法,如果是非抽象方法,将会覆盖它。

    

Arbitrary method replacement(任意方法替换)



    类person,
    
        public class Person {                    public void sayMsg(String msg){                //相应的逻辑代码            }                    }    



    类ReplacePerson
    
    import org.springframework.beans.factory.support.MethodReplacer;    public class ReplacePerson implements MethodReplacer{            @Override        public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable {                        System.out.println(arg0);            System.out.println(arg1);            System.out.println(Arrays.toString(arg2));                //com.link2.Person$$EnhancerBySpringCGLIB$$c6b26e0e@950e31        //public void com.link2.Person.sayMsg(java.lang.String)        //[上午大家好]                                return null;        }        }


    
    
    配置文件中定义了两个实体类的bean,明确指定了person类中被替换的方法,和替换方法的bean实例
        
   
        <bean id="replaceperson" class="com.link2.ReplacePerson"></bean>                <bean id="person" class="com.link2.Person">            <replaced-method name="sayMsg" replacer="replaceperson"></replaced-method>        </bean>



0 0
原创粉丝点击