Chaos2018

Springboot重新加载Bean

Springboot重新加载Bean

背景:

       有一个需求是要获取第三方的接口,加载到本地,通过本地调用接口获取结果,第三方接口会有版本变动,前端会有点击事件获取最新版本。

设计:

      考虑到并不是每次都需要重新获取第三方接口,我将第三方接口以Configuration和bean的形式放入配置类中,示例代码如下:

@Configuration
public class DemoConfiguration {
    @Bean(name="execute")
    public static Execute getBean(){
        //TODO
//Execute是我逻辑中需要的类
Execute execute = ....(逻辑过程省略)
return execute; } }

      后续的问题是,当第三方版本变动的时候,不能通过重启服务获取新的版本,而是重新加载配置类,获取新的实例,经过多方查找资料,汇总如下:

mport org.springframework.context.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DemoController {
    @Autowired
    private ApplicationContext applicationContext;
    @ResponseBody
    @PostMapping("/getVersion")
    public void reloadInstance(){
        //获取上下文
        DefaultListableBeanFactory defaultListableBeanFactory =
                (DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
        //销毁指定实例 execute是上文注解过的实例名称 name="execute"
        defaultListableBeanFactory.destroySingleton("execute");
        //按照旧有的逻辑重新获取实例,Excute是我自己逻辑中的类
        Execute execute = DemoConfiguration.getBean();
        //重新注册同名实例,这样在其他地方注入的实例还是同一个名称,但是实例内容已经重新加载
        defaultListableBeanFactory.registerSingleton("execute",execute);
    }

}

经过验证可行。

posted on 2021-07-19 16:58  Chaos2018  阅读(3765)  评论(1编辑  收藏  举报

导航