[Spring] @AutoWired @Resource 区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012099869/article/details/72729897

1、AutoWired 为spring提供的注解,Resource 为 J2EE 提供,在 javax.annotation.Resource 包下,但spring支持该注解;

2、AutoWired 按 byType 注入,想按名称注入,可结合 @Qualifer(value = “”) 。且默认不允许依赖的对象为 null,可设置 required = false 允许 null;

Resource 按 byName, byType 注入,指定 name 则按byName方式,指定 type 则按byType方式。如果未指定 name,则按字段名查找,找不到时才按照 type 进行匹配;

用法如下:

@Autowired
private BBB b;

@Resource
private CCC c;

@Autowired
@Qualifier(value = "bbb")
private BBB b;

@Resource(name = "ccc")
private CCC c;

3、@Resource 的作用相当于 @Autowired,只不过 @Autowired 按byType自动注入。

类的位置:

org.springframework.beans.factory.annotation.Autowired

javax.annotation.Resource

猜你喜欢

转载自blog.csdn.net/u012099869/article/details/72729897