首页 > 其他分享 >@Resource、@Autowired和@Inject的对比与总结

@Resource、@Autowired和@Inject的对比与总结

时间:2023-03-08 22:23:36浏览次数:42  
标签:Resource Autowired default Spring Inject ElementType

@Resource

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {

    String name() default "";

    String lookup() default "";

    Class<?> type() default java.lang.Object.class;

    enum AuthenticationType {
	    CONTAINER,
	    APPLICATION
    }

    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;

    boolean shareable() default true;

    String mappedName() default "";

    String description() default "";
}

@Resourcejavax.annotation 包中,属于 JSR-250 规范,是 Java 标准的注解;

@Resource 常用在字段上标注,也能在 setter 方法上标注;

@Resource 支持在类上标注,表示该类是一个组件类,需要注入容器,但是 Spring 框架并不支持这个功能(Spring 框架下应该使用 @Component@Controller@Service@Repository@Bean 标注组件类);

@Resource 根据以下顺序在 IoC 容器中寻找 Bean:

  1. 名称
  2. 类型
  3. @Qualifier 声明

@Autowired

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

	boolean required() default true;

}

@Autowired 常用在字段上标注,也能在 setter 方法上标注;

@Autowired 根据以下顺序在 IoC 容器中寻找 Bean:

  1. 类型
  2. @Qualifier 声明
  3. 名称

@Inject

@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Inject {
}

@Inject 需要引入依赖:

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

@Injectjavax.inject 包中,属于 JSR-330 规范,也是 Java 标准的注解;

@Inject 既能在字段上标注,也能在 setter 方法上标注,还能在构造器上标注;

@Inject 根据以下顺序在 IoC 容器中寻找 Bean:

  1. 类型
  2. @Qualifier 声明
  3. 名称

这点与 @Autowired 相同

笔者在三者之间的选择

  1. 在实际工作中,从来没见过 @Inject 的使用,开发者都是在 @Resource@Autowired 之间选择;
  2. 因为 Spring 的影响力巨大,所以 @Autowired 使用率相比 @Resource 更高;
  3. @Resource 出现在 @Autowired 之后,这时候 @Autowired 已经有了一定的使用量,所以 @Resource 的使用率赶不上 @Autowired
  4. @Resource 是作为 Java 标准出现的,目的是在编程语言层面上有通用的依赖注入注解,而不是受 Spring 生态绑架,即相同的代码,如果想把 IoC 容器从 Spring Framework 切换为其它,这时候字段上的 @Resource 就不需要修改;而如果是 @Autowired, 则因为移除了 Spring Framework 相关依赖,所以不得不修改为 @Resource 或者新 IoC 容器的注解(虽然这几乎是不可能发生的事,毕竟在 Java Web 开发领域,与其说是 Java 带着 Spring 飞,不如说是 Spring 拖着 Java 走);
  5. @Resource@Autowired 两者的依赖查找顺序在实际开发中影响并不大,只需要注意有所不同即可,如果同一个类在容器中有多个 Bean,则通过 @Qualifier 明确声明 Bean 的名称即可;
  6. 在笔者目前使用的 IDEA IntelliJ 2023.3.3 中,使用 @Autowired 会被 IDE 波浪线警告(不建议使用字段注入),但使用 @Resource 则不会有这个警告。另外,就如面向对象的依赖反转原则(Dependency inversion principle,DIP),Java 标准就像是接口,而 Spring 则只是一种实现,依赖接口而不是依赖实现,所以个人倾向于使用 @Resource
  7. 无论选择哪一个注解,实际使用并不会有什么大的区别,混合使用也没有问题,但为了保持一致,在同一项目中最好只选用一个。

参考

Wiring in Spring: @Autowired, @Resource and @Inject

What is a Spring Bean?

标签:Resource,Autowired,default,Spring,Inject,ElementType
From: https://www.cnblogs.com/lancefoxtsai/p/17196482.html

相关文章