There are several ways that this could be done. One of my preferred way is to provide configuration of data sources via properties file. Here is a sample property file for postgresql:
pg.datasource.url=jdbc:postgresql://db-server-bar:5432/app-db pg.datasource.username=root pg.datasource.password=toor pg.datasource.driver-class-name=org.postgresql.Driver
Now you can create configuration class for each datasource:
public class BarDbConfig { @Bean(name = "pgDataSource") @ConfigurationProperties(prefix = "pg.datasource") public DataSource dataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "barEntityManagerFactory") public LocalContainerEntityManagerFactoryBean barEntityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("pgDataSource") DataSource dataSource ) { return builder .dataSource(dataSource) .packages("com.app.domain") .persistenceUnit("pg") .build(); } }
For a detailed tutorial, you can refer to this tutorial.
There can also be situations where you would like to switch databases at runtime. In which case, you can use something called AbstractRoutingDataSource. A detailed tutorial on how to use this feature can be found at Spring's official blog site.