java - Spring中如何更新数据源bean?

标签 java spring spring-boot datasource javabeans

我的目标是使用 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/

    相关文章:

    java - 无法在 Spring 工具套件中解析 @GetMapping

    java - spring-mvc 中不同类的角色

    spring-boot - 使用 Spring WebFlux 和 OAuth 2.0 登录时如何注销?

    java - 如何检查 OutputStream 是否已关闭

    java - 根据用户输入使用 Quartz 创建动态 Spring Batch 作业

    java - 如何将数据从 Activity 发送到 java 类

    java - 使用 ReactiveCouchbaseRepository 时出现 IllegalArgumentException 期望找到类 rxSingle 的响应式(Reactive)适配器,但无法找到

    java - HTTP 状态 400 - 客户端发送的请求在语法上不正确。 Spring MVC

    mysql - Hibernate 和 MySql 的 Hikaricp : one of either dataSource or dataSourceClassName must be specified

    java - 我在哪里可以找到 xuggler 简单教程?