问题
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