前言
这篇博客是对【@Resource 源码解析】做的另一个补丁。主要会讲解在使用@Resource的时候发生的expected single matching bean but found 2异常在源码层面是一个怎么样子的过程。为什么要用@Resource讲解,因为这个注解比较好模拟异常的发生,实际上@Autowired发生的原理也是一样的。更多Spring内容进入【Spring解读系列目录】。
问题还原
首先要有一个接口Demo,然后有两个实现类DemoImpl1和DemoImpl2,以及一个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

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

被折叠的 条评论
为什么被折叠?



