Search code examples
javaspringspring-bootdatasourcejavabeans

How to update datasource bean in Spring?


My goal is to create a Webserver with Spring. It has to implement Multitenancy, which works great if you don't make it dynamic (adding, removing, changing). Is it possible to update the datasource bean in Spring?

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;
    }

}

What I've tried:

CustomRoutingDataSource c = context.getBean(CustomRoutingDataSource.class);
c.setTargetDataSources(CustomRoutingDataSource.getCustomDatasources());

which updates the bean(?) but doesn't update Spring's datasources, database connections are still missing if added with this method.


Solution

  • Simple solution for those with the same problem:

    Add @RefreshScope

        @Bean
        @RefreshScope
        public DataSource dataSource() {
            CustomRoutingDataSource customDataSource = new CustomRoutingDataSource();
            ...
            return customDataSource;
        }
    

    Add spring actuator endpoint in pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
    1. POST to /actuator/refresh to update datasources!