Srikar Appal Srikar Appal - 3 months ago 16
Java Question

Java Spring Recreate specific Bean

I want to re-create (new Object) a specific bean at Runtime (no restarting the server) upon some DB changes. This is how it looks -

@Component
public class TestClass {

@Autowired
private MyShop myShop; //to be refreshed at runtime bean

@PostConstruct //DB listeners
public void initializeListener() throws Exception {
//...
// code to get listeners config
//...

myShop.setListenersConfig(listenersConfig);
myShop.initialize();
}

public void restartListeners() {
myShop.shutdownListeners();
initializeListener();
}
}


This code does not run as
myShop
object is created by Spring as Singleton & its context does not get refreshed unless the server is restarted. How to refresh (create a new object)
myShop
?

One bad way I can think of is to create new
myShop
object inside
restartListeners()
but that does not seem right to me.

Answer

In DefaultListableBeanFactory you have public method destroySingleton("beanName")so you can play with it, but you have to be aware that if your autowired your bean it will keep the same instance of the object that has been autowired in the first place, you can try something like this:

@RestController
public class MyRestController  {

        @Autowired
        SampleBean sampleBean;

        @Autowired
        ApplicationContext context;
        @Autowired
        DefaultListableBeanFactory beanFactory;

        @RequestMapping(value = "/ ")
        @ResponseBody
        public String showBean() throws Exception {

            SampleBean contextBean = (SampleBean) context.getBean("sampleBean");

            beanFactory.destroySingleton("sampleBean");

            return "Compare beans    " + sampleBean + "==" 

    + contextBean;

    //while sampleBean stays the same contextBean gets recreated in the context
            }

    }

It is not pretty but shows how you can approach it. If you were dealing with a controller rather than a component class, you could have an injection in method argument and it would also work, because Bean would not be recreated until needed inside the method, at least that's what it looks like. Interesting question would be who else has reference to the old Bean besides the object it has been autowired into in the first place,because it has been removed from the context, I wonder if it still exists or is garbage colected if released it in the controller above, if some other objects in the context had reference to it, above would cause problems.