MirroredFate
MirroredFate

Reputation: 12835

How to prevent a singleton bean from being destroyed by the ApplicationContext refresh

I have a singleton bean that is being destroyed when the ApplicationContext is being refreshed. This bean is the session registry, which keeps track of sessions (duh). I use the refresh from the ApplicationContext to get the new configuration after my application has been initially configured. However, the SessionRegistry should NOT be destroyed since the session itself has not ended. Thus, I need to exclude the SessionRegistry from the wanton destruction caused by ApplicationContext's refresh. Is there a reasonably simple way to do this, or must I implement my own version of the ApplicationContext, and recode its methods?

EDIT: So what I ended up doing was overriding the sessionregistry to make a true singleton, getting all the sessions from the session registry, removing the sessionregistry as a listner from the applicationcontext, and then adding the sessions back in after the sessionregistry was recreated.

Upvotes: 1

Views: 1496

Answers (1)

Bozho
Bozho

Reputation: 597342

I guess you can use @PreDestroy method to transfer the current state to a static field, and read that field on @PostConstruct to restore the bean data.

Note that spring beans are singleton within the context. If the context dies, the bean dies. And a bean can have multiple instances if multiple contexts exists. Hence the use of static which is "more singleton".

Upvotes: 1

Related Questions