无状态Bean的作用域一般可以配置singleton单例模式,如果我们往singleton的Boss中注入prototype的Car,并希望每次调用Boss Bean的getCar()时都能够返回一个新的Car Bean,使用传统的zhurufangshi8将无法实现这样的要求。因为singleton的Bean注入关联Bean的动作只有一次,虽然Car Bean的作用域是prototype类型,但Boss 通过getCar()返回对象还是最开始注入的那个Car Bean.
如果希望每次提哦用getCar()都返回一个新的Car Bean的实例,一种可选的方法就是让Boss实现BeanFactoryAware接口,让Boss能够访问容器的引用,这样Boss的getCar() 方法就可以采取以下的实现方式来达到目的:
public Car getCar() {
return (Car)factory.getBean("car");
}
我们可以通过方法注入的方案完美的解决这个问题。
package com.lxm.injectfun;
public interface MagicBoss{
Car getCar();
}
下面我们不编写任何实现类,仅通过装配为该接口提供动态的实现,让getCar()接口方法每次都返回新的Car Bean:
<bean id="car" class="com.lxm.injictfun,Car" scope="prototype">
<property name="brand" value="红旗CA72/>
<property name="price" value="2000"/>
</bean>
<bean id="magicBoss" class="com.lxm.injictfun.MagicBoss">
<lookup-method name="getCar" bean="car"/>
</bean>
通过lookup-method 元素标签为MagicBoss的getCar()提供动态实现,返回prototype的car Bean,这样Spring将在运行期为MagicBoss接口提供动态实现,其效果 等同于:
package com.lxm.injictfun;
....
public class MagicBossimpl implements MagicBoss,ApplicationContextAware{
private ApplicationContext ctx;
public Car getcar() {
return (Car)ctx.getBean("car");
}
public void setApplicationContext(ApplicationContext ctx) throws BeanException{
this.ctx=ctx;
}
}
因为每次调用MagicBoss 的getCar()方法,都从容器中获取car Bean,由于car Bean的作用域为prototype,所以每次都返回新的car实例。