多个@bean无法通过@resource注入对应的bean(org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found )


一、异常

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 2: masterDataSource,slaveDataSource

二、场景分析

看异常提示这个类型”javax.sql.DataSource“的bean期待一个单例bean但是发现了2个:masterDataSource,slaveDataSource。看打印的堆栈:

 如上,我们发现有个DataSourceInitializer.init方法追踪进去:

这里就给了我们一个灵感,DataSourceInitializer这个数据源初始化是spring boot自动配置类启动的。如下图

继续追踪异常:最终定位在DefaultListableBeanFactory.resolveNamedBean()中如下代码块:

如上图第一,第二个箭头分别取@Primary和@Priority2种注解注释的bean,只要存在,就可以获取bean并返回。

三、解决方案

1. 在其中一个bean上加@Primary,使得自动配置时不报错。

1 @ConfigurationProperties(prefix = "study.datasource.master")
2 @Bean(name = "masterDataSource")
3 @Primary
4 public DataSource masterDataSource() {
5 }

 

2. 在启动类注解:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



猜您在找 Caused by:org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type "" available: expected at least 1 bean which qualifies as autowire candidate 在springboot启动报错:No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} 解决hibernate项目添加集成jpa使用EntityManager时报错No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 2: sessionFactory,entityManagerFactory Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.thinkplatform.dao.UserLogDao' available: expected at least 1 bean which qualifies as autowi springboot启动报错:Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.zxkj.lockserver.dao.CompanyDao' available: expected at least 1 bean which qua org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.yang.service.StudentInterface' available: expected at least 1 bean which qualifies as autowire candidate org.springframework.beans.factory.NoSuchBeanDefinitionException:No qualifying bean of type 'xxx 'available MyBatis Plus:No qualifying bean of type 'com.baomidou.mybatisplus.mapper.BaseMapper' available: expected single matching bean but found 4 required a bean of type 'javax.sql.DataSource' that could not be found. springmvc注入类 NoUniqueBeanDefinitionException: No qualifying bean of type [] is defined: expected single错误
 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM