1

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.

Nonononoki
  • 63
  • 2
  • 7
  • Just make many datasources and use one or the other. – Zorglube Aug 08 '19 at 14:52
  • Possible duplicate of [dynamically change Spring data source](https://stackoverflow.com/questions/13507522/dynamically-change-spring-data-source) – Ori Marko Aug 11 '19 at 09:03
  • @user7294900 It's not, I also want my backend to also handle a dynamic number of datasource - not predefined datasources and switching between them (this already works for me) – Nonononoki Aug 12 '19 at 06:32

1 Answers1

4

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!
stringy05
  • 6,511
  • 32
  • 38
Nonononoki
  • 63
  • 2
  • 7