spring实现的bean自动注入在项目开发中是一个经常使用到的功能,但自动装配两个或多个bean时,会抛出NoUniqueBeanDefinitionException:No qualifying bean of type 'com' available: expected single matching bean but found 2异常。最常见的现象就是一个接口有两个实现类。spring允许一个类创建两个或多个bean。但如果bean是自动装配的,就会抛出异常。
原因分析
spring应用程序启动时,应用程序将beans加载到ApplicationContext中,接着添加依赖bean生成其他类型bean,如果两个或多个bean可用于为一个bean注入,则会抛出NoUniqueBeanDefinitionException:No qualifying bean of type 'com' available: expected single matching bean but found异常。
异常演示
public interface Animal { public String noise(); }
1 2 3 4 5 6 7 | @Component public class Dog implements Animal{ @Override public String noise() { return "bowwow" ; } } |
1 2 3 4 5 6 7 | @Component public class Bea implements Animal{ @Override public String noise() { return "buzz" ; } } |
1 2 3 4 5 | @Service public class Zoo { @Autowired public Animal animal; } |
如此,工程启动便会抛出异常。
解决方案
方案一
Autowired使用java约定变量名,如dog是Dog的约定变量名,所以,使用注解@Autowired可以将Dog变量名命名为dog,如下
1 2 3 4 5 6 | @Service public class Zoo { @Autowired public Animal dog; } |
方案二
如果类的数据类型与加载的bean类型匹配,bean将会自动装载为对应的类型。所以,不用接口或抽象类名定义bean,具体实现如下
1 2 3 4 5 6 | @Service public class Zoo { @Autowired public Dog animal; } |
方案三
可以使用注解@Primary,Spring的@Primary注解,是框架在3.0版中引入的。其作用与功能,当有多个相同类型的bean时,使用@Primary来赋予bean更高的优先级。代码如下
1 2 3 4 5 6 7 8 | @Component @Primary public class Dog implements Animal{ @Override public String noise() { return "bowwow" ; } } |
方案四
spring注解@Qualifier用于从多个bean中选择一个bean。@Qualifier 注释将被配置为匹配 bean 名称。@Autowired 注释使用限定符的名称来匹配和加载 bean。
1 2 3 4 5 6 7 | @Service public class Zoo { @Autowired @Qualifier ( "dog" ) public Animal animal; } |
方案五
限定符与方法参数一起使用。
1 2 3 4 5 6 7 8 | @Service public class Zoo { private Animal animal; @Autowired public vod setAnimal( @Qualifier ( "dog" ) Animal animal){ this .animal = animal; } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?