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 对象。