How to reinitialize a Spring Bean? How to reinitialize a Spring Bean? spring spring

How to reinitialize a Spring Bean?


You have three options to update singleton bean in spring context, you can chose one suitable for your use case:

Reload method In the Bean
Create a method in your bean which will update/reload its properties. Based on your trigger, access the bean from spring context, and then call the reload method to update bean properties (since singleton) it will also be updated in spring context & everywhere it is autowired/injected.

Delete & Register Bean in Registry
You can use DefaultSingletonBeanRegistry to remove & re-register your bean. The only drawback to this, it will not refresh/reload old instance of already autowired/injected bean in consumer classes.

DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) context.getBeanFactory();registry.destroySingleton({yourbean}) //destroys the bean objectregistry.registerSingleton({yourbeanname}, {newbeanobject}) //add to singleton beans cache

@RefreshScope
Useful for refreshing bean value properties from config changes. But it has very limited & specific purpose. Resource to read more about it.