Spring中如何更新数据源bean?

Non*_*oki 1 java spring datasource javabeans spring-boot

我的目标是用 Spring 创建一个 Web 服务器。它必须实现多租户,如果您不使其动态(添加、删除、更改),它会非常有效。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;
    }

}
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

CustomRoutingDataSource c = context.getBean(CustomRoutingDataSource.class);
c.setTargetDataSources(CustomRoutingDataSource.getCustomDatasources());
Run Code Online (Sandbox Code Playgroud)

它更新了bean(?)但不更新Spring的数据源,如果使用此方法添加,数据库连接仍然丢失。

Non*_*oki 5

对于有同样问题的人来说,简单的解决方案:

添加@RefreshScope

    @Bean
    @RefreshScope
    public DataSource dataSource() {
        CustomRoutingDataSource customDataSource = new CustomRoutingDataSource();
        ...
        return customDataSource;
    }
Run Code Online (Sandbox Code Playgroud)

在 pom.xml 中添加弹簧执行器端点

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
  1. POST 到/actuator/refresh更新数据源!