我的目标是使用 Spring 创建一个 Web 服务器。它必须实现 Multi-Tenancy ,如果您不使其动态(添加、删除、更改),它会非常有效。 Spring中是否可以更新数据源bean?
我的代码:
@SpringBootApplication
public 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的数据源,如果使用此方法添加数据库连接仍然丢失。
最佳答案
对于有相同问题的人来说,简单的解决方案:
添加@RefreshScope
@Bean
@RefreshScope
public DataSource dataSource() {
CustomRoutingDataSource customDataSource = new CustomRoutingDataSource();
...
return customDataSource;
}
在 pom.xml 中添加 Spring 执行器端点
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- POST 到
/actuator/refresh
以更新数据源!
关于java - Spring中如何更新数据源bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57415119/