我的目標是使用 Spring 創(chuàng)建一個 Web 服務(wù)器。它必須實現(xiàn)多租戶,如果您不使其動態(tài)化(添加、刪除、更改),它會很好用。是否可以在 Spring 中更新數(shù)據(jù)源 bean?我的代碼:@SpringBootApplicationpublic class MyApplication { public static void main(String[] args) throws IOException { SpringApplication.run(MyApplication.class, args); } //Multitenancy @Bean public DataSource dataSource(){ //implements AbstractRoutingDataSource CustomRoutingDataSource customDataSource = new CustomRoutingDataSource(); //logic here return customDataSource; }}我試過的:CustomRoutingDataSource c = context.getBean(CustomRoutingDataSource.class);c.setTargetDataSources(CustomRoutingDataSource.getCustomDatasources());它更新 bean(?) 但不更新 Spring 的數(shù)據(jù)源,如果使用此方法添加,數(shù)據(jù)庫連接仍然丟失。
1 回答

HUWWW
TA貢獻1874條經(jīng)驗 獲得超12個贊
對于有同樣問題的人的簡單解決方案:
添加@RefreshScope
@Bean
@RefreshScope
public DataSource dataSource() {
CustomRoutingDataSource customDataSource = new CustomRoutingDataSource();
...
return customDataSource;
}
在 pom.xml 中添加彈簧執(zhí)行器端點
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
POST 到/actuator/refresh更新數(shù)據(jù)源!
添加回答
舉報
0/150
提交
取消