@Autowired注解到底是byType还是byName?
网上的文章已经很多了,这里就不说太多废话,开门见山。
@Autowired是spring的注解,默认使用的是byType的方式向Bean里面注入相应的Bean。例如:
@Autowired
private UserService userService;
这段代码会在初始化的时候,在spring容器中寻找一个类型为UserService的bean实体注入,关联到userService的引入上。
但是如果UserService这个接口存在多个实现类的时候,就会在spring注入的时候报错,具体如下:
public class UserService1 implements UserService
public class UserService2 implements UserService
当存多个UserService的实现类时,错误信息如下:
2016-08-05 14:53:53,795 ERROR [org.springframework.test.context.TestContextManager] - <Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@14a2f921] to prepare test instance [UserServiceTest@3c87521]>
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private yjc.demo.service.UserService UserServiceTest.userService; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [yjc.demo.service.UserService] is defined: expected single matching bean but found 2: userService1,userService2
抛出了org.springframework.beans.factory.BeanCreationException,而原因是注入的时候发现有2个匹配的bean,但是不知道要注入哪一个:expected single matching bean but found 2: userService1,userService2
那么如何应对多个实现类的场景呢,看一下代码:
@Autowired
private UserService userService1;
@Autowired
private UserService userService2;
@Autowired
@Qualifier(value = "userService2")
private UserService userService3; @Test
public void test(){
System.out.println(userService1.getClass().toString());
System.out.println(userService2.getClass().toString());
System.out.println(userService3.getClass().toString());
}
运行结果:
class yjc.demo.serviceImpl.UserService1
class yjc.demo.serviceImpl.UserService2
class yjc.demo.serviceImpl.UserService2
运行结果成功,说明了2种处理多个实现类的方法:
1.变量名用userService1,userService2,而不是userService。
通常情况下@Autowired是通过byType的方法注入的,可是在多个实现类的时候,byType的方式不再是唯一,而需要通过byName的方式来注入,而这个name默认就是根据变量名来的。
2.通过@Qualifier注解来指明使用哪一个实现类,实际上也是通过byName的方式实现。
由此看来,@Autowired注解到底使用byType还是byName,其实是存在一定策略的,也就是有优先级。优先用byType,而后是byName。
最新文章
- light oj 1422 Halloween Costumes (区间dp)
- keyup keydown keypress 区别
- 安装PL/SQL Developer 遇到的问题及解决方法
- checkbox的完美用户体验(转)
- 草珊瑚的css基础
- Objective-C 中 NULL、nil、Nil、NSNull 的定义及不同
- iOS 进阶 第十八天(0423)
- IOS 学习日志 2015-3-16
- 使用Fiddler捕获Java程序中的HTTP请求
- ASP.NET中Partial Class部分类
- OpenCV使用边缘提取、腐蚀、轮廓进行车牌定位
- 普实软件:MES机器数据维护
- 一张图搞懂容器所有操作 - 每天5分钟玩转 Docker 容器技术(26)
- LeetCode 55. Jump Game (跳跃游戏)
- 利用JS判断浏览器种类
- NIO的初步入门
- javaScript中的redirect
- Generative Adversarial Nets
- andorid UI事件
- mark1-git
热门文章
- Windows 系统常用命令
- scikit-learn 中的 KMeans
- 目标检测论文解读13——FPN
- dapi 基于Django的轻量级测试平台四 任务设置
- [KCOJ3393]上马
- Visual Studio调试XSLT
- es4x 调用其他三方jar 包
- ESA2GJK1DH1K升级篇: STM32远程乒乓升级,基于WIFI模块AT指令TCP透传方式,定时访问升级(含有数据校验)
- 【线段树】【P4062】 [Code+#1]Yazid 的新生舞会
- haproxy 配置文件详解 之 defaults