Srikar Appal Srikar Appal - 1 year ago 60
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 -

public class TestClass {

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

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


public void restartListeners() {

This code does not run as
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)

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

Answer Source

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:

public class MyRestController  {

        SampleBean sampleBean;

        ApplicationContext context;
        DefaultListableBeanFactory beanFactory;

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

            SampleBean contextBean = (SampleBean) context.getBean("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.