Creating JPA repositories dynamically depending on the request attributes

Viewed 62

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.

1 Answers

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.

Related