Is there any way to inject or set up data source to Crud Repository? I need one repository and multiple database with same schema. I tried to make hash map with database name and data source and use something like that https://spring.io/blog/2007/01/23/dynamic-datasource-routing/ but it doesn't work
Asked
Active
Viewed 1,658 times
1
-
Refer link : [Spring-boot multiple datasource](http://stackoverflow.com/questions/27614301/spring-boot-multiple-datasource) and [Use multiple database with spring](http://stackoverflow.com/questions/30362546/how-to-use-2-or-more-databases-with-spring) these questions solve your problem. – Amit khanduri Oct 30 '15 at 02:49
-
No, they aren't because I need exactly one repository and one DAO. I just figured out how to do this. Thank you for your help. – mariusz2108 Oct 30 '15 at 14:33
-
can you provide the solution as an answer (you can accept you own answer) – Y.M. Nov 02 '15 at 10:28
1 Answers
0
This solved my problem
@Component
public class RoutingDataSource extends AbstractRoutingDataSource {
@Autowired
private DatabaseMap databaseMap;
@Override
public void afterPropertiesSet() {
setTargetDataSources(databaseMap.getSourcesMap());
setDefaultTargetDataSource(databaseMap.getSourcesMap().get("DEFAULT"));
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getDatabaseType();
}
}
@Configuration
public class DatabaseLoader {
@Bean
public DatabaseMap databaseMap() {
//init databases using DataSourceBuilder
return databaseMap;
}
}
I change context same way as here https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

mariusz2108
- 851
- 2
- 11
- 36
-
Can you please put the code inside databaseMap function from DatabaseLoader? – georgiana_e Jan 31 '18 at 07:54