Spring学习(十九)Bean 的方法注入和方法替换介绍

来源:互联网 发布:isis网络恐怖主义活动 编辑:程序博客网 时间:2024/06/06 12:37
lookup方法注入指容器能够重写容器中bean的抽象或者具体方法,从而返回查找容器中其他bean的结果。

Spring IoC容器拥有复写bean方法的能力,这项功能主要归功与cglib这个类包,cglib类包可以在运行时动态的操作class字节码,他能够为Bean动态的创建子类或者实现类。所以使用lookup方法注入的时候必须在项目中加入cglib类包。

那么现在我们定义一个MagicBoss接口,并且在接口中我们声明一个getCar接口方法。
public Interface MagicBoss{    Car getCar();}
下面我们可以不编写任何的实现类,仅仅通过配置而不编写任何的实现类便为该接口提供动态的实现。让getCar方法每次都能返回一个新的car实例。
<bean id="car" class="cn.lovepi.***.Car"    p:brand="红旗CA72" p:price="2666" scope="prototype"/><bean id="magicBoss" class="cn.lovepi.***.MagicBoss">    <lookup-method name="getCar" bean="car"/></bean>

这样Spring将在运行期为MagicBoss提供动态的接口实现。他的效果就等同于如下的代码:
public class MagicBossImpl implements MagicBoss,ApplicationContextAware{    private ApplicationContext ctx;    public Car getCar(){        return (Car)ctx.getBean("car");    }    public void setApplicationContext(ApplicationContext ctx){        this.ctx=ctx;    }}
注意
lookup方法注入是有使用条件的:一般希望一个singleton的bean返回时变为一个prototype的bean的时候使用。

replaced方法替换实现MethodReplacer接口,替换目标Bean的方法

我们来看一下如下的两端代码:
public class Boss1 implements MagicBoss{    public Car getCar(){        Car car=new Car();        car.setBrand("宝马");        return car;    }}public class Boss2 implements MethodReplacer{    public Object reimplement(Object arg0,Method arg1,Object[] arg2){        Car car=new Car();        car.setBrand("美人豹");        return car;    }}
可以看到在Boss2中实现了MethodReplacer接口,在接口方法reimplement当中返回了一辆美人豹汽车。
为了替换其他的bean就必须实现MethodReplacer接口,Spring将利用该接口方法来替换目标Bean。

接下来我们利用Spring的配置文件来实现使用Boss2的方法来替换Boss1的方法。
那么请看如下的配置文件:
<bean id="boss2" class="cn.lovepi.injectfun.Boss2"/><bean id="boss1" class="cn.lovepi.injectfun.Boss1"/>    <replaced-method name="getCar" replacer="boss2"></replaced-method></bean>

可以看到配置文件中配置了使用boss2的getCar方法来替换boss1中的对应方法。



0 0
原创粉丝点击