源码解析异常expected single matching bean but found 2是如何发生的

本文解析了在Spring框架中使用@Resource注解时出现expectedsinglematchingbeanbutfound2异常的原因及过程。通过示例说明当Spring容器无法确定具体注入哪一个实现类时,将如何触发该异常。

前言

这篇博客是对【@Resource 源码解析】做的另一个补丁。主要会讲解在使用@Resource的时候发生的expected single matching bean but found 2异常在源码层面是一个怎么样子的过程。为什么要用@Resource讲解,因为这个注解比较好模拟异常的发生,实际上@Autowired发生的原理也是一样的。更多Spring内容进入【Spring解读系列目录】

问题还原

首先要有一个接口Demo,然后有两个实现类DemoImpl1DemoImpl2,以及一个DemoService去依赖Demo。当我们在上面的例子中使用@Resource时,如果变量名字不符合Spring命名规则,而项目里也没有指定一个命名规则怎么办。这个问题其实很容易模拟,比如修改一下DemoService的内容如下。

public class DemoService {
   
   
    @Resource
    Demo demo;
}

报错实例

Spring自动注入其实还有一个常见的问题,那就是expected single matching bean but found 2的异常。类似上述例子的写法,当Spring容器不知道应该为接口注入哪个实例对象的时候就会报下面的异常

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.bean.Demo' available: expected single matching bean but found 2: demoImpl1,demoImpl2
   at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:321)
   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415)
   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608)
   at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531)
   at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
   at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
   at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
   at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
   at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
   at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
   at org.spr
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值