数据源注入到 Crud Repository spring boot [英] Data source inject to Crud Repository spring boot

查看:59
本文介绍了数据源注入到 Crud Repository spring boot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将数据源注入或设置到 Crud Repository?我需要一个存储库和多个具有相同架构的数据库.我试图用数据库名称和数据源制作哈希映射,并使用类似的东西 https://spring.io/blog/2007/01/23/dynamic-datasource-routing/ 但它不起作用

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

推荐答案

这解决了我的问题

@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;
    }
}

我以与此处相同的方式更改上下文 https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

I change context same way as here https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

这篇关于数据源注入到 Crud Repository spring boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆