问题描述
我试图将prototype
bean注入到singleton
bean中,以使对单例bean方法的每个新调用都具有原型bean的新实例.
I am trying to inject a prototype
bean in a singleton
bean such that every new call to a singleton bean method has a new instance of the prototype bean.
考虑如下所示的单例豆:
Consider a singleton bean as below:
@Component
public class SingletonBean {
@Autowired
private PrototypeBean prototypeBean;
public void doSomething() {
prototypeBean.setX(1);
prototypeBean.display();
}
}
我希望每次调用doSomething()
方法时,都会使用一个新的PrototypeBean
实例.
I expect that every time the doSomething()
method is called, a new PrototypeBean
instance is utilized.
下面是原型bean:
@Component
@Scope(value="prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class PrototypeBean {
Integer x;
void setX(Integer x) {
this.x = x;
}
void display() {
System.out.println(x);
}
}
似乎正在发生的事情是,Spring急于在doSomething()
方法中移交PrototypeBean的新实例.也就是说,doSomething()
方法中的两行代码在每一行中都创建了prototypeBean的新实例.
What seems to be happening is that spring is being overeager in handing over a new instance of PrototypeBean in the doSomething()
method. That is, the 2 lines of code in the doSomething()
method are creating a new instance of prototypeBean in each line.
因此在第二行-prototypeBean.display()
打印 NULL .
此注入的配置中缺少什么?
What is missing in configuration for this injection?
推荐答案
从Spring :
对于版本3.2 文档,文档似乎有所更改在这里可以找到这句话:
It seems the documentation has changed a bit for version 3.2 documentation where you can find this sentence:
似乎不希望您使用代理原型Bean,因为每次向BeanFactory
请求它时,都会创建它的新实例.
It seems that its not expected you use a proxied prototype bean, as each time it is requested to the BeanFactory
it will create a new instance of it.
要为原型bean建立某种工厂,可以使用ObjectFactory
,如下所示:
In order to have a kind of factory for your prototype bean you could use an ObjectFactory
as follows:
@Component
public class SingletonBean {
@Autowired
private ObjectFactory<PrototypeBean> prototypeFactory;
public void doSomething() {
PrototypeBean prototypeBean = prototypeFactory.getObject();
prototypeBean.setX(1);
prototypeBean.display();
}
}
和原型bean将声明如下:
and your prototype bean would be declared as follows:
@Component
@Scope(value="prototype")
public class PrototypeBean {
// ...
}
这篇关于Spring Prototype范围内的bean在单例中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!