【Java报错】多数据源mapper异常more than one `primary` bean found among candidates: [sqlSessionFactory] 问题分析解决
起因项目使用了多个数据源,但是没有使用持久层框架,后期加入了mybatis-plus插件,启动项目时报错,信息如下:2021-08-19 09:16:20 ERROR [,,,] [main] o.s.boot.SpringApplication - Application run failedorg.springframework.beans.factory.BeanCreationExcept
1. 报错分析
项目使用了多个数据源,但是没有使用持久层框架,后期加入了 mybatis-plus 插件,启动项目时报错,信息如下:
2021-08-19 09:16:20 ERROR [,,,] [main] o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'xxxComponent': Injection of resource dependencies failed;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'xxxMapper' defined in file [E:\xxx\BaseMapper.class]:
Unsatisfied dependency expressed through bean property 'sqlSessionFactory';
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException:
No qualifying bean of type 'org.apache.ibatis.session.SqlSessionFactory' available:
more than one 'primary' bean found among candidates:
[sqlSessionFactory_greenplum, sqlSessionFactory_oracle]
重要信息是 【more than one ‘primary’ bean found among candidates:
[sqlSessionFactory_greenplum, sqlSessionFactory_oracle]】 我看了一下项目的编码信息,如下【确实是2个 ✌️ 】:
@Bean(name = "sqlSessionFactory_greenplum")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("ds_greenplum") DataSource dataSource)
throws Exception {}
@Bean(name = "sqlSessionFactory_oracle")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("ds_oracle") DataSource dataSource)
throws Exception {}
@Primary注解可以标注出【有多个候选者有资格自动装配单值依赖项时,优先考虑的Bean对象】之前项目没有报错,说明 SqlSessionFactory 对象并不是自动装配对象,也就是说可以去掉其中一个 @Primary 就能解决问题,但是你敢随便去掉注解吗?你敢吗?🐶 反正我不敢 😅 只能寻求其他方法。
2. 问题解决
这里只贴出核心代码:
@SpringBootApplication
@MapperScan(basePackages = {"com.*.*.**.persistence"},
sqlSessionFactoryRef = "sqlSessionFactory_greenplum")
@EnableScheduling
public class SpringBootApplicationStart {}
使用 basePackages 标注出你的 mapper 文件所在的文件夹,使用 sqlSessionFactoryRef 标注出你的 mapper 文件使用的 SqlSessionFactory 对象。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)