How to programatically change databases in Spring with one DataSource?

蓝咒 提交于 2019-11-28 18:57:32
Abhinav Sarkar

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
gerrytan

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!