简体   繁体   中英

Creating JPA repositories dynamically depending on the request attributes

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-1.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 JPA repo. Similarly, if header values is "dev-1" then inject the corresponding datasource.

Any inputs will be appreciated.

Create a datasource for each database you want to connect to, such as explained here Spring Boot configure and use two data sources . Then retrieve the request header from the HTTP request by using the @RequestHeader Spring Web Annotation. Then you can implement a method such as DataSource getDatasourceForHeader(String header) which returns the datasource for the respective HTTP header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM