java如何在春季更新数据源bean?
我的目标是用Spring创建一个Web服务器。它必须实现多租户,如果您不将其动态化(添加、删除、更改),这将非常有效。有可能在春季更新数据源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的数据源,如果使用此方法添加,数据库连接仍然丢失
# 1 楼答案
针对相同问题的简单解决方案:
添加
@RefreshScope
在pom中添加弹簧执行器端点。xml
/actuator/refresh
更新数据源李>