我的目标是用 Spring 创建一个 Web 服务器。它必须实现多租户,如果您不使其动态化(添加、删除、更改),它会非常有效。 Spring中是否可以更新数据源bean?
My code:
@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的数据源,如果使用此方法添加数据库连接仍然丢失。
对于有同样问题的人来说,简单的解决方案:
Add @RefreshScope
@Bean
@RefreshScope
public DataSource dataSource() {
CustomRoutingDataSource customDataSource = new CustomRoutingDataSource();
...
return customDataSource;
}
在 pom.xml 中添加弹簧执行器端点
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- POST to
/actuator/refresh
更新数据源!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)