Spring FactoryBean和范围一起工作 [英] Spring FactoryBean and scopes working together
问题描述
我想一起使用FactoryBeans和范围.具体来说,我希望将由FactoryBean创建并返回的对象放入指定的(也许是自定义的)范围内.问题是要执行以下操作:
I'd like to use FactoryBeans and scopes together. Specifically, I'd like the object created and returned by a FactoryBean to be placed into a specified (perhaps custom) scope. The issue is that doing the following:
<bean class="x.y.z.TestFactoryBean" scope="test" />
导致FactoryBean本身具有作用域,并且在工厂创建的对象上具有某些不可预测的行为.我明白为什么会这样;工厂本身是一流的春季管理Bean,并且具有自己的生命周期.但是,我找不到指定工厂返回的对象本身的作用域的方法.
Results in the FactoryBean itself being scoped, and has somewhat unpredictable behaviour on the object created by the factory. I understand why this is; the factory itself is a first-class spring-managed bean, and has its own lifecycle. However, I can't find a way to specify that the object returned from the factory should itself be scoped.
另一方面,这正是我想要的(只要TestFactoryBean不实现FactoryBean接口):
On the other hand, this does exactly what I want (as long as TestFactoryBean does NOT implement the FactoryBean interface):
<bean class="x.y.z.TestFactoryBean" name="testFactory">
<bean class="x.y.z.TestBean" factory-bean="testFactory"
factory-method="getObject" scope="test" />
真正的问题是,如何使用真正的FactoryBeans使Spring表现得像上面第二个示例一样?
So the real question is, how can I make Spring behave like it does for the 2nd example above, but using real FactoryBeans?
推荐答案
您不能轻易地对从FactoryBean
返回的bean使用自定义范围.
You can't easily use a custom scope on a bean returned from a FactoryBean
.
来自Spring的 Java文档:
FactoryBeans可以支持单例和原型
FactoryBeans can support singletons and prototypes
如果希望FactoryBean
的返回的bean具有原型范围,则必须实现isSingleton()
方法,如下所示:
If you want the FactoryBean
's returned bean to have the prototype scope, then you must implement the isSingleton()
method like this:
public class TestFactoryBean implements FactoryBean<TestBean> {
// the rest of the required methods are removed for simplicity reasons..
public boolean isSingleton() {
return false;
}
}
要支持自定义范围,您必须自己实现逻辑,并且不会很直观,因为FactoryBean
仅提供isSingleton()
方法.对于具有自定义范围的bean,我宁愿建议使用FactoryBean
之外的其他解决方案.
To support a custom scope, you have to implement the logic yourself and it will not be very intuitive, since the FactoryBean
only provides the isSingleton()
method. I will rather recommend using another solution than FactoryBean
for beans with custom scope.
希望这会有所帮助!
这篇关于Spring FactoryBean和范围一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!