spring 方法注入之 方法以替换

在spring Ioc 容器里,允许用一个Bean 的方法去替换另一个Bean 的方法。

public class ForestTwo implements MethodReplacer {
    public ForestTwo() {
      super ();
    }
    public Object reimplement(Object arg0, Method arg1, Object[] arg2)
         throws Throwable {
     Tree tt = new Tree();
     tt.setName( "桂花" );
      return tt;
    }
}

  public class Forest {
    private Tree tree ;
    public Tree getTree() {
     Tree reTree = new Tree();
     reTree.setName( "柳树" );
      return reTree;
    }
    public void setTree(Tree tree) {
      this . tree = tree;
    }
    public Forest() {
      super ();
    }
    public Forest(Tree tree) {
      super ();
      this . tree = tree;
    }
}


配置一

      < bean id = "forest" class = "com.aowin.modle.Forest" >   </ bean >
      < bean id = "forest2" class = "com.aowin.modle.ForestTwo" />
System. out .println( forest .getTree().getName());
输出的是---柳树


配置二
< bean id = "forest" class = "com.aowin.modle.Forest" >
      < replaced-method name = "getTree" replacer = "forest2" ></ replaced-method >
  </ bean >
              
  < bean id = "forest2" class = "com.aowin.modle.ForestTwo" />
System. out .println( forest .getTree().getName());
输出的是 桂花。
用于替换他人的Bean必须实现 MethodReplacer接口
因为 forest2 实现了  MethodReplacer 接口,重写了该接口下的  reimplement()方法。
当  forest 调用getTree方法时,就会被 forest2替换掉,用 重写了的  reimplement()方法去替换。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值