浅谈SpringBoot @Autowired的两种注入方式
作者:简单随风 时间:2021-06-28 06:08:34
Autowired有两种注入方式
by type
by name
默认使用的是byType的方式向Bean里面注入相应的Bean。例如:
@Autowired
private UserService userService;
这段代码会在初始化的时候,在spring容器中寻找一个类型为UserService的bean实体注入,关联到userService的引入上。
但是如果UserService这个接口存在多个实现类的时候,就会在spring注入的时候报错,例如:
public class UserService1 implements UserService
public class UserService2 implements UserService
此时会报错 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。
来源:https://juejin.cn/post/6979177662581473316
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android仿京东搜索框渐变效果
![](https://img.aspxhome.com/file/2023/0/114350_0s.gif)
基于WPF实现步骤控件的示例代码
![](https://img.aspxhome.com/file/2023/9/91389_0s.jpg)
SpringBoot2使用JTA组件实现基于JdbcTemplate多数据源事务管理(亲测好用)
![](https://img.aspxhome.com/file/2023/4/66964_0s.jpg)
Android开发Jetpack组件DataBinding用例详解
![](https://img.aspxhome.com/file/2023/9/88349_0s.gif)
手写Java LockSupport的示例代码
![](https://img.aspxhome.com/file/2023/9/119049_0s.png)
使用IDEA异常断点来定位java.lang.ArrayStoreException的问题
![](https://img.aspxhome.com/file/2023/9/75499_0s.png)
C# 获取PDF中的数字签名证书
![](https://img.aspxhome.com/file/2023/8/113878_0s.png)
Spring Boot应用事件监听示例详解
详解spring-boot集成elasticsearch及其简单应用
![](https://img.aspxhome.com/file/2023/4/60594_0s.png)
Mybatis返回插入的主键问题解决方案
JAVA HashMap详细介绍和示例
![](https://img.aspxhome.com/file/2023/2/88742_0s.jpg)
java设计模式之适配器模式
![](https://img.aspxhome.com/file/2023/4/59854_0s.jpg)
SpringBoot整合Mybatis与thymleft实现增删改查功能详解
![](https://img.aspxhome.com/file/2023/2/118822_0s.png)
SpringBoot用配置影响Bean加载@ConditionalOnProperty
![](https://img.aspxhome.com/file/2023/2/75482_0s.jpg)
Spring AOP底层源码详解
Spring底层事务原理解析
Unity计时器功能实现示例
![](https://img.aspxhome.com/file/2023/8/88408_0s.gif)
Java并发编程之闭锁与栅栏的实现
Android使用GPS获取用户地理位置并监听位置变化的方法
![](https://img.aspxhome.com/file/2023/8/92628_0s.png)