Java面试:@Resource 和 @Autowired 的区别?

1、来源不同

  • @Autowired:​Spring 自身提供的注解,位于 org.springframework.beans.factory.annotation 包中。​
  • @Resource:​Java标准中的注解,位于 javax.annotation 包中。

2、注入方式不同

  • @Autowired:​默认按照类型(byType)进行自动注入。它会在 Spring 容器中查找匹配的类型进行注入。如果存在多个相同类型的 Bean,可以结合 @Qualifier 注解或 @Primary 注解来指定具体的 Bean。

1

2

@Autowired

private UserService userService;

  • @Resource:​默认按照名称(byName)进行注入。它首先根据名称匹配 Bean,如果找不到匹配的名称,则按照类型进行匹配。@Resource 注解有两个重要的属性:name 和 type。如果指定了 name,则按照名称进行注入;如果未指定 name,则默认取变量名作为 Bean 的名称进行查找。

1

2

@Resource(name = "userServiceImpl")

private UserService userService;

3、支持的参数不同

  • @Autowired:​仅包含一个参数 required,表示是否必须注入,默认值为 true。如果将其设置为 false,则在无法找到匹配的 Bean 时,不会抛出异常。
1
2
@Autowired (required =  false )
private   UserService userService;
  • @Resource:​包含多个参数,其中最常用的是 name 和 type。name 用于指定要注入的 Bean 的名称,type 用于指定要注入的 Bean 的类型。​
1
2
@Resource (name =  "userService" , type = UserService. class )
private   UserService userService;

目前在项目中一般使用 @Resource,因@Resource是Java标准中的注解,更契合些。我们在IDEA中使用@Autowired注解时,IDEA会在@Autowired下打个波浪线,给你说是不推荐的。

跟 @Resource 和 @Autowired 功能相似的注解

  • @Qualifier:​当存在多个相同类型的 Bean 时,@Qualifier 可与 @Autowired 配合使用,指定具体注入的 Bean。
1
2
3
@Autowired
@Qualifier ( "specificUserService" )
private   UserService userService;
  • @Primary:​当存在多个相同类型的 Bean 时,可以在其中一个 Bean 上使用 @Primary 注解,标识其为主要的候选者,优先注入该 Bean。

1

2

3

4

5

@Primary

@Component

public class PrimaryUserServiceImpl implements UserService {

    // 实现细节

}

 Java面试、学习文档、进阶路线、算法、架构资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值