@Resource 和 @Autowired 的区别

发布于:2025-04-01 ⋅ 阅读:(24) ⋅ 点赞:(0)

1、来源不同

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

2、注入方式不同

  • @Autowired:​默认按照类型(byType)进行自动注入。它会在 Spring 容器中查找匹配的类型进行注入。如果存在多个相同类型的 Bean,可以结合 @Qualifier 注解或 @Primary 注解来指定具体的 Bean。
@Autowired
private UserService userService;
  • @Resource:​默认按照名称(byName)进行注入。它首先根据名称匹配 Bean,如果找不到匹配的名称,则按照类型进行匹配。@Resource 注解有两个重要的属性:name 和 type。如果指定了 name,则按照名称进行注入;如果未指定 name,则默认取变量名作为 Bean 的名称进行查找。
@Resource(name = "userServiceImpl")
private UserService userService;

3、支持的参数不同

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

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

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

  • @Qualifier:​当存在多个相同类型的 Bean 时,@Qualifier 可与 @Autowired 配合使用,指定具体注入的 Bean。
@Autowired
@Qualifier("specificUserService")
private UserService userService;
  • @Primary:​当存在多个相同类型的 Bean 时,可以在其中一个 Bean 上使用 @Primary 注解,标识其为主要的候选者,优先注入该 Bean。
@Primary
@Component
public class PrimaryUserServiceImpl implements UserService {
    // 实现细节
}

老早就想把这两个注解的区别记录下了。今天终于如愿以偿了。

有些人,你用言语劝告根本不起作用,必须让他亲身经历失败,他才会得到真知。-- 烟沙九洲


网站公告

今日签到

点亮在社区的每一天
去签到