Reinitialize bean in spring at runtime

I am wondering if there is an option to recreate the bean that was already created in the java config when the web application starts.

What I want to do is reconfigure the bean settings.

For example, I create a new bean path to the database:

     @Bean
     public TestBean getTestBean() {
         TestBean tb = new TestBean("some_path_taken_from_external_point");
         return tb;
     }

      

At runtime, I want to change the path. Let's assume this bean does not have a setter method for the database path. I will have some kind of event and a listener for this event. The listener must reinitialize the TestBean in a new way.

Is it possible?

I was thinking about some kind of wrapper. In this case, I will have a TestBeanWrapper class that will have a get () method that will return a TestBean instance and recreate (String path), which will create a new object with the given path.

I'm not sure if such a wrapper would work for me, since TestBean is a class from an external library and I'm not sure if it was not injected somewhere (but it probably wasn't injected).

It is more likely that other beans can rely on the TestBean, so they must be reinitialized as well (in case they don't have settings for my TestBean).

Is this possible in Spring (4.1)? What is the best approach for such cases?

+3


source to share


1 answer


So, I'm still not sure why you want to change the path, but I have 2 suggestions:

1. Look at the Bean area setup. By setting the scope of the bean, you can restore the bean based on the context. See Bean Areas for more information.



2. Look at perhaps using a controller or service. Controllers and services let you get getters and setters that can give you more control.

0


source







All Articles