springboot通过接口重新加载某个bean
# springboot通过接口重新加载某个bean
背景:
有一个需求是要获取第三方的接口,加载到本地,通过本地调用接口获取结果,第三方接口会有版本变动,前端会有点击事件获取最新版本。
设计:
考虑到并不是每次都需要重新获取第三方接口,我将第三方接口以Configuration和bean的形式放入配置类中,示例代码如下:
@Configuration
public class DemoConfiguration {
@Bean(name="execute")
public static Execute getBean(){
//TODO
//Execute是我逻辑中需要的类
Execute execute = ....(逻辑过程省略)
return execute;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
后续的问题是,当第三方版本变动的时候,不能通过重启服务获取新的版本,而是重新加载配置类,获取新的实例,经过多方查找资料,汇总如下:
import 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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
经过验证可行。
编辑 (opens new window)
上次更新: 2024/01/26, 05:03:22
- 01
- python使用生成器读取大文件-500g09-24
- 02
- Windows环境下 Docker Desktop 安装 Nginx04-10
- 03
- 使用nginx部署多个前端项目(三种方式)04-10