I used to create external properties files, which can be added as many as possible. I read the properties into a Map<Key, properties> for each properties file.
@PostConstruct
public void properties() throws Exception{
// read properties and put them into map
crmPropertiesMap.put(key, properties);
}
@Bean(name = "crmPropertiesMap")
public Map<String, CRMProperties> getCrmPropertiesMap() {
return crmPropertiesMap;
}
And create new DataSource for each properties file then put them into another map Map<Key, DataSource>.
@Bean
public Map<String, DataSource> dataSourceMap() {
Map<String, DataSource> dataSourceMap = new HashMap<>();
for( CRMProperties crmProperties : crmPropertiesMap.values())
{
// create DataSource
dataSourceMap.put(crmProperties.getHotelName(),
DataSourceBuilder.create()
.url(crmProperties.getSpringDatasourcePrimaryUrl())
.driverClassName(crmProperties.getSpringDatasourcePrimaryDriverClassName())
.username(crmProperties.getSpringDatasourcePrimaryUsername())
.password(crmProperties.getSpringDatasourcePrimaryPassword())
.build());
Then create SqlSession
private SqlSession createSqlSession(String id) {
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment(id, transactionFactory, dataSourceMap.get(id));
Configuration configuration = new Configuration(environment);
configuration.addMapper(SaleInfoMapper.class);
return new SqlSessionTemplate(sqlSessionFactoryBuilder.build(configuration));
}
@Bean
public Map<String, SqlSession> sqlSessionMap() {
Map<String, SqlSession> sqlSessionMap = new HashMap<>();
for ( String id : dataSourceMap.keySet() )
{
sqlSessionMap.put(id, createSqlSession(id));
}
return sqlSessionMap;
}
Then get SqlSession dynamically.
SqlSession sqlSession = sqlSessionMap.get(key);
Hope this helps you.