Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reinitialize a Spring Bean?

Is it possible to reinitialize a Spring Bean on runtime?

My Bean uses static settings which in some cases changes and then i have to reinitialize the bean.

like image 759
Fip Avatar asked Jul 06 '18 21:07

Fip


People also ask

How do you refresh spring beans?

Refresh scope beans are lazy proxies that initialize when they are used (i.e. when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call you just need to invalidate its cache entry.

How do I remove a spring context from a bean?

A spring bean can be removed from context by removing its bean definition. BeanDefinitionRegistry factory = (BeanDefinitionRegistry) context. getAutowireCapableBeanFactory(); factory. removeBeanDefinition("mongoRepository");

How are spring beans initialized?

Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.


1 Answers

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 object
registry.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.

like image 53
Amith Kumar Avatar answered Sep 16 '22 17:09

Amith Kumar