使用springboot 整合多数据源 遇到的坑

背景描述

在生产环境中需要区分测试用户和生成用户,产生的数据需要存储到不同的数据库,方便后期数据统计和处理

问题展示

在使用springboot整合多数据源时,项目启动一直报错,错误如下:
The dependencies of some of the beans in the application context form a cycle:

产生问题的代码如下:

@Configuration
public class DynamicDataSourceConfig {

    @Bean("firstDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.first")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.second")
    public DataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("dataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.TYPE_PFMSC, firstDataSource);
        targetDataSources.put(DataSourceType.TYPE_PFMSC_TEST, secondDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }

}

根据图中的引用圈可以看 出
1.创建sqlSessionFactory时需要dataSource
2.创建dataSource的时候,需要创建firsrDataSource和secondDataSource
3.然后创建firstDataSource时需要DataSourceInitializerInvoker
4.DataSourceInitializerInvoker又会去引用dataSource造成循环引用

解决办法

@Configuration
public class DynamicDataSourceConfig {

    @Bean("firstDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.first")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.second")
    public DataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("dataSource")
    @DependsOn({ "firstDataSource", "secondDataSource"})
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.TYPE_PFMSC, firstDataSource);
        targetDataSources.put(DataSourceType.TYPE_PFMSC_TEST, secondDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }

}

加入注解@DependsOn({ “firstDataSource”, “secondDataSource”})后可以解决上述问题.
该注解用于声明当前bean依赖于另外一个bean。所依赖的bean会被容器确保在当前bean实例化之前被实例化.

但是为什么加入这个注解之后可以让这个引用圈的引用关系发生变化,本菜鸟还没有彻底弄清楚,还请路过的大神指点一二.

学习资料整理

本人作为Java开发菜鸡,平时也收集了很多学习视频,在此分享给大家一起学习

整套VIP学习视频

在这里插入图片描述

架构师相关视频

在这里插入图片描述

扫码领取

在这里插入图片描述

更多资料链接

Java免费学习视频下载
Python免费学习视频下载
Web前端免费学习视频下载
人工智能免费学习视频下载
大数据免费学习视频下载
UI设计免费学习视频下载

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值