有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    针对相同问题的简单解决方案:

    添加@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>
    
    1. 发布到/actuator/refresh更新数据源