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

背景描述

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

问题展示

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

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

产生问题的代码如下:

@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实例化之前被实例化.

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

相关文章:

  • 2021-04-16
  • 2021-11-02
  • 2022-12-23
  • 2022-02-09
  • 2021-09-15
  • 2022-01-09
  • 2022-03-10
猜你喜欢
  • 2021-09-24
  • 2022-12-23
  • 2022-12-23
  • 2021-06-12
  • 2022-12-23
  • 2021-07-10
  • 2021-12-06
相关资源
相似解决方案