How to programmatically change databases in Spring with one DataSource?

后端 未结 2 422
鱼传尺愫
鱼传尺愫 2020-12-08 08:49

I\'m looking to see what\'s the best way to use one DataSources in Spring but be able to switch the database from within the Java code? Below are my two DataSources and the

相关标签:
2条回答
  • 2020-12-08 09:07

    You can do this by extending the Spring's AbstractRoutingDataSource and wrapping your existing data sources in it. Check this article for details. Quoting from the article:

    The general idea is that a routing DataSource acts as an intermediary – while the 'real' DataSource can be determined dynamically at runtime based upon a lookup key.

    Also see similar questions on SO:

    1. Using AbstractRoutingDataSource to dynamically change the database schema/catalog
    2. Reading from multiple Db's with same Persistence Unit?
    3. How to create Dynamic connections (datasource) in spring using JDBC
    0 讨论(0)
  • 2020-12-08 09:12

    There are many ways you can do this. For example, you can create a service class DatasourceSelectorService, and based on some input (eg: configuration file/user input) it chooses the datasource's bean accordingly.

    All other classes requiring a datasource should obtain it via this DatasourceSelectorService.

    0 讨论(0)
提交回复
热议问题