@Autowired与@Resource与@Reference注
2020-09-25 本文已影响0人
HachiLin
在说明这三者的区别前,先了解一下Spring自动装配byName和byType区别。
1. byName与byType
1.1 byName
byName会搜索整个配置文件中的bean,如果有相同名称的bean则自动配置,否则显示异常。
1.2 byType
byType会搜索整个配置文件中的bean,如果有相同类型的bean则自动装配,否则显示异常。
2. @Autowired
@Autowired按byType自动注入,是有Spring提供的注解,需要导入包org.springframework.beans.factory.annotation.Autowired。
3. @Resource
@Resource默认按byName自动注入,是由J2EE提供的注解,需要导入包javax.annotation.Resource。
3.1 @Resource装配属性
@Resource有两个重要的属性name和type:
①如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常。
②如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常。
③如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或是找到多个,都会抛出异常。
④如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。
3.2 @Resource与@Autowired相转换
以下两段代码是等价的
- @Autowired
public class TestServiceImpl {
@Autowired
@Qualifier("userDao")
private UserDao userDao;
}
- @Resource
public class TestServiceImpl {
@Resource(name="userDao")
private UserDao userDao; // 用于字段上
}
4. @Reference
@Reference是dubbo注解,它注入的是分布式的远程服务对象,需要dubbo配置使用。在微服务中,工程项目会分成很多模块(Maven工程),每个模块相当于一个服务,一个服务调用另一个服务的功能需要使用@Reference注解。
参考文献
- https://blog.csdn.net/qq_39429962/article/details/81176085
- https://blog.csdn.net/x_iya/article/details/73385486?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.channel_param