spring-data-jpa 根据请求属性动态创建JPA存储库

c9x0cxw0  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(169)

I have a requirement like one API REST endpoint which will be connected to 3 databases. In this API, three service implementations, each service will connect to separate database.
I have to use Spring data JPA to get the data from the database.
I am using AbstractRoutingDataSource to create the datasource during application start up.
I have registered 3 datasource beans using application context and planning to create 3 JPA configs in 3 different packages.
Here, My question is to how to map the datasource to JPA repo depending on the request header.
Example:
This is the configuration value
datasource.environment = dev.db2, dev.postgres, dev.mysql
This list of environments may vary like in UAT, we may have uat1.db2, uat2.postgres. This list is dynamic.
In the above scenario I have registered 3 datasource beans using application context.
If the request header value is "dev" then need to inject the dev datasource into corresponding JPA repo.
Similarly, if header values is "dev-1" then inject the corresponding datasource.
Any inputs will be appreciated.

w6mmgewl

w6mmgewl1#

为您要连接的每个数据库创建一个数据源,如这里所述的Spring Boot configure and use two data sources。然后使用@RequestHeader Spring Web Annotation从HTTP请求中检索请求标头。然后您可以实现一个方法,如DataSource getDatasourceForHeader(String header),该方法为相应的HTTP标头返回数据源。

相关问题