Using Multiple DataSource In Spring Boot App

1. Overview

Spring Boot will load properties from the file which resides in the application class path and add them to the Spring Environment.

This post shows how to create multiple JdbcTemplate instances which are bounded to different databases specified in the properties files.

2. The

Sample properties file located at src/main/resources


3. Configuration for DB

Configure DataSource bean in the Spring configuration class named DbConfig. Using @ConfigurationProperties we could bind the namespace properties to the given DataSource bean.

public class DbConfig {

	@Bean(name = "mysqlDb")
	public DataSource mysqlDataSource() {
		return DataSourceBuilder.create().build();
	@Bean(name = "sqliteDb")
	public DataSource sqliteDataSource() {
		return DataSourceBuilder.create().build();
	@Bean(name = "mysql")
    public JdbcTemplate mysqlJdbcTemplate(@Qualifier("mysqlDb") DataSource mysqlDb) { 
		return new JdbcTemplate(mysqlDb); 
	@Bean(name = "sqlite") 
    public JdbcTemplate sqliteJdbcTemplate(@Qualifier("sqliteDb") DataSource sqliteDb) { 
        return new JdbcTemplate(sqliteDb); 

5. Create an interface for the DAO

Write an abstract method inside the MedicaidDao interface

public interface MedicaidDao {
	Map<String, String> findMetaDataOfTemplateBxp();

6. Implement the DAO interface

Autowire the JdbcTemplate to a field and use @Qualifier annotation to specify which bean should be injected to it.

public class MedicaidDaoImpl implements MedicaidDao {

	static final Logger LOG = LoggerFactory.getLogger(MedicaidDaoImpl.class);

	private JdbcTemplate jdbcTemplate;

	private JdbcTemplate sqliteJdbcTemplate;

	public Map<String,String> findMetaDataOfTemplateBxp() {
		Map<String,String> bxpMetaDataMap =  new HashMap<String,String>();
		jdbcTemplate.query("SELECT column_name, column_type FROM INFORMATION_SCHEMA.columns where table_schema=? and table_name=?", (ps) -> {
		},(rs) -> {
		return bxpMetaDataMap;

7. Conclusion

DataSourceBuilder builds data source from the values specified in the properties file.

Using the @Qualifier annotation we could specify the JdbcTemplate bean which should be injected in the DAO. Data will be fetched from the data source bounded to the bean.