原型组件的Spring事件处理 [英] Spring Event Handling for prototype components
问题描述
假设我有两个分量X和Y,其中X是单例,而Y不是.
Let say I have two components X and Y, where X is singleton and Y is not.
当我发布XUpdateEvent时,没有问题,我可以捕获该事件.但是,对于YUpdateEvent,我无法捕获事件. Spring为每个激发的事件创建新实例,而不使用已创建的实例.
when I publish XUpdateEvent, there is no problem, I can catch the event. However, for YUpdateEvent's I cannot catch events. Spring creates new instances for each fired event, not using the already created ones.
那么,我是否需要编写一个自定义范围?或EventListener有设置?
So, Should I need to write a custom scope? or EventListener has settings?
说明:
@Component
public class X{
@EventListener
public void onUpdate(XUpdateEvent event){
// fine.
}
}
@Component
@Scope("prototype")
public class Y{
@EventListener
public void onUpdate(YUpdateEvent event){
// calls new instance of Y for each event.
// Event should be fired for created instances.
}
}
推荐答案
Spring为每个触发的事件创建新实例,而不使用 已经创建的
Spring creates new instances for each fired event, not using the already created ones
这就是原型作用域的含义.看看文档.
This is what prototype scope means. Have a look at the docs.
bean部署的非单一原型范围导致 每次针对特定的请求创建一个新的bean实例 豆被制成.
The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made.
如果您希望Spring重用您的Y
实例,请将其声明为单例(即完全不定义@Scope
)
If you want that Spring reuses your Y
instance, declare it as singleton (i.e. define no @Scope
at all)
这篇关于原型组件的Spring事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!