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); } }
經過驗證可行。