Spring Event Handling for prototype components

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-14 14:33:09

问题


Let say I have two components X and Y, where X is singleton and Y is not.

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.

So, Should I need to write a custom scope? or EventListener has settings?

To illustrate:

@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.
 }
}

回答1:


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.

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.

If you want that Spring reuses your Y instance, declare it as singleton (i.e. define no @Scope at all)



来源:https://stackoverflow.com/questions/33368341/spring-event-handling-for-prototype-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!