背景描述
在生产环境中需要区分测试用户和生成用户,产生的数据需要存储到不同的数据库,方便后期数据统计和处理
问题展示
在使用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设计免费学习视频下载