Kim Rudolph

Spring DataSource Routing

A default setup of spring-data applications is a package with Entity definitions and one with Repository definitions. There is a solution for using those same entities against multiple databases without starting a second application.

Use cases are

The following example shows a solution for a single tool with access to development, testing and production data. It enables data display migration without the need to export and import data to another format. That might not be the best choice for most applications as it opens the door to accidently modifiying data in the wrong environment.

The example is based on Spring Boot. Selected dependencies at are JPA and Cache.

The source code with tests is available at

Defining multiple Environments

As mentioned, there are three defined environments.

public enum DatabaseEnvironment {

The current DatabaseEnvironment is held in a ThreadLocal based context.

public class DatabaseContextHolder {

    private static final ThreadLocal<DatabaseEnvironment> CONTEXT =
        new ThreadLocal<>();

    public static void set(DatabaseEnvironment databaseEnvironment) {

    public static DatabaseEnvironment getEnvironment() {
        return CONTEXT.get();

    public static void clear() {


Switching the context is achieved by setting the DatabaseEnvironment.


Configuring the DataSource Routing

Spring Boot provides a lot of AutoConfiguration magic, including DataSource setup. That needs to be excluded.

@SpringBootApplication(exclude = { 
    HibernateJpaAutoConfiguration.class })
public class RoutingApplication {

    public static void main(String[] args) {, args);

Using AbstractRoutingDataSource enables the mapping between the actual DataSources and the DatabaseEnvironment.

public class DataSourceRouter extends AbstractRoutingDataSource {

    protected Object determineCurrentLookupKey() {
        return DatabaseContextHolder.getEnvironment();

Disabling the AutoConfiguration enables a custom configuration of the DataSource initialization.

@EnableJpaRepositories(basePackageClasses = CustomerRepository.class, 
                       entityManagerFactoryRef = "customerEntityManager", 
                       transactionManagerRef = "customerTransactionManager")
public class DatasourceConfiguration {


DataSources for each environment are defined by prefixed properties. Mandatory properties are jdbcUrl, username and password. See the file for a full example.

@ConfigurationProperties(prefix = "app.customer.development.datasource")
public DataSource customerDevelopmentDataSource() {
    return DataSourceBuilder.create().build();

@ConfigurationProperties(prefix = "app.customer.testing.datasource")
public DataSource customerTestingDataSource() {
    return DataSourceBuilder.create().build();

@ConfigurationProperties(prefix = "app.customer.production.datasource")
public DataSource customerProductionDataSource() {
    return DataSourceBuilder.create().build();

A Map filled with those DataSources is used by the DataSourceRouter to select the DataSource that belongs to the current environment.

public DataSource customerDataSource() {
    DataSourceRouter router = new DataSourceRouter();

    final HashMap<Object, Object> map = new HashMap<>(3);
    map.put(DatabaseEnvironment.DEVELOPMENT, customerDevelopmentDataSource());
    map.put(DatabaseEnvironment.TESTING, customerTestingDataSource());
    map.put(DatabaseEnvironment.PRODUCTION, customerProductionDataSource());
    return router;

The last part of the configuration is the default JPA/Hibernate boilerplate code. The JPA prefix enables shared configurations like

@Autowired(required = false)
private PersistenceUnitManager persistenceUnitManager;

public JpaProperties customerJpaProperties() {
    return new JpaProperties();

public LocalContainerEntityManagerFactoryBean customerEntityManager(
    final JpaProperties customerJpaProperties) {

    EntityManagerFactoryBuilder builder =

    return builder.dataSource(customerDataSource()).packages(Customer.class)

public JpaTransactionManager customerTransactionManager(
    @Qualifier("customerEntityManager") final EntityManagerFactory factory) {
    return new JpaTransactionManager(factory);

private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(
    JpaProperties customerJpaProperties) {
    JpaVendorAdapter jpaVendorAdapter =
    return new EntityManagerFactoryBuilder(jpaVendorAdapter,
        customerJpaProperties.getProperties(), this.persistenceUnitManager);

private JpaVendorAdapter createJpaVendorAdapter(
    JpaProperties jpaProperties) {
    AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    return adapter;

What about Caching?

Manually configuring cache key attributes (@Cacheable( key = "...")) will cause bugs, because they are not environment aware. The solution is using only @Cacheable without key attributes and adding a global KeyGenerator.

public class CachingConfiguration extends CachingConfigurerSupport {

    public KeyGenerator keyGenerator() {
        return new EnvironmentAwareCacheKeyGenerator();


That custom KeyGenerator sets the current database environment as a prefix.

public class EnvironmentAwareCacheKeyGenerator implements KeyGenerator {

    public Object generate(Object target, Method method, Object... params) {

        String key = DatabaseContextHolder.getEnvironment().name() + "-" + (
            method == null ? "" : method.getName() + "-") + StringUtils
            .collectionToDelimitedString(Arrays.asList(params), "-");

        return key;


Adding more DataSources with multiple Environments

It is possible to add another DataSourceConfiguration if there is the need to connect to other databases. The prefix would be something like app.contracts.. Entity and Repository classes have to be in a separate package. An additional EntityManager will be available and needs to be sprecified with a unit name, e.g. @PersistenceContext(unitName = "contractEntityManager") if injected. Be aware that the already existing DataSource needs to be definied as @Primary.