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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值