In my Spring boot application, we utilize @RefreshScope
for dynamic reloading of beans after configuration changes. It works, but I have encountered an issue when combining the @RefreshScope
on beans with methods annotated @PostConstruct
and @PreDestroy
. It seems the @PostConstruct
is not called after refresh.
When booting the app, the @PostConstruct
method is called normally. When invoking refresh, the @PreDestroy
method gets invoked normally as well, and I would expect @PostConstruct
to be called on the new proxied bean instance, but it is not. There is important init/destroy-logic going on in these methods, so not having them called is a problem.
Anyone encountered the same problem, and is this a bug or a "feature"? Is there a way to make this work?
Best regards
I faced the same problem today and was able to solve it by calling a method on the @RefreshScope
'd bean after the refresh. To accomplish this, I added an event handler for the RefreshScopeRefreshedEvent
to the affected bean:
@EventListener
public void onRefreshScopeRefreshed(final RefreshScopeRefreshedEvent event) {
getClass();
}
As you can see it's a quite meaningless implementation, but nevertheless this method call on the bean triggers its initialization (the @PostConstruct
method).
This behaviour conforms to the documentation:
Refresh scope beans are lazy proxies that initialize when they are used (i.e. when a method is called),
But still I think that it's really a bug and that @PostConstruct
should be called automatically after a refresh.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With