@Resource和@Autowired区别

@Resource和@Autowired都是用来做依赖注入的,但他们存在几点不同:

1.来源不同

@Resource来源于Java定义的注解,来自于JSR-250

@Autowired来自于Spring定义的注解

2.支持参数不同

@Resource 支持七个参数

  • name:资源的JNDI名称。在spring的注入时,指定bean的唯一标识。
  • type:指定bean的类型。
  • lookup:引用指向的资源的名称。它可以使用全局JNDI名称链接到任何兼容的资源。
  • authenticationType:指定资源的身份验证类型。它只能为任何受支持类型的连接工厂的资源指定此选项,而不能为其他类型的资源指定此选项。
  • shareable:指定此资源是否可以在此组件和其他组件之间共享。
  • mappedName:指定资源的映射名称。
  • description:指定资源的描述。

@Autowired 仅支持一个参数requied

3.依赖查找顺序不同

@Resource先根据name查找对象,如果通过name找不到,则通过类型查找

@Autowired和Resource相反,即先查找类型,再查找name

4.注入规则不同

@Autowired支持:属性注入,构造方法注入,Setter注入

@Resource只支持:属性注入,Setter注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 //属性注入  
@Autowired
private UserService userService;

// 构造方法注入
public class UserController {

private UserService userService;

@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
}


// Setter 注入
public class UserController {

private UserService userService;

@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}

5.编译器报错

@Autowired编译器会报错(不影响运行)

image-20240303000251494

@Resource不存在报错

image-20240303000321589