多个@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方法追踪进去:

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

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

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

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

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

如上图第一,第二个箭头分别取@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})

 

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