Java Spring Recreate specific Bean

后端 未结 2 1400
南笙
南笙 2020-12-31 04:42

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          


        
2条回答
  •  死守一世寂寞
    2020-12-31 05:28

    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.

提交回复
热议问题