问题
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
回答1:
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/
来源:https://stackoverflow.com/questions/33400162/data-source-inject-to-crud-repository-spring-boot