Data source inject to Crud Repository spring boot

扶醉桌前 提交于 2019-12-12 03:24:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!