Java SpringBoot @Autowired @Resource @Inject
在Spring中依赖注入可以使用@Autowired@Resource@Inject来完成,并且在一般的使用中是可以相互替换的(注意是一般),不过三者还是有区别,他们三者的区别如下:

@Autowired

  1. Spring本身替换的注解(org.springframework.beans.factory.annotation.Autowired),需要导入Spring相应的jar包才能使用
  2. 可以标注的位置:构造器、方法、方法参数、变量域和注解上面

    1. @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface Autowired {
    5. boolean required() default true;
    6. }
  3. 在Spring容器解析@Autowired注解时,使用的后置处理器为AutowiredAnnotationBeanPostProcessor,在这个后置处理的注释中有这么一段: ```java {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessor}

  • implementation that autowires annotated fields, setter methods, and arbitrary
  • config methods. Such members to be injected are detected through annotations:
  • by default, Spring’s {@link Autowired @Autowired} and {@link Value @Value}
  • annotations. *
  • Also supports JSR-330’s {@link javax.inject.Inject @Inject} annotation,

  • if available, as a direct alternative to Spring’s own {@code @Autowired}. ```
  1. @Autowired注解有一个required属性,当指定required属性为false时,意味着在容器中找相应类型的bean,如果找不到则忽略,而不报错(这一条是两个注解所没有的功能)。
  2. 默认优先按照类型去容器中找对应的组件,找到就赋值,如果找到多个相同类型的组件,再将属性的名称作为组件的id去容器中查找,如果组件id对象的bean不存在,而且required属性为true,就报错。
  3. 支持@Primary注解,让Spring进行自动装配的时候,默认使用首选的bean。

    @Resource

  4. JSR250规范提供的注解(javax.annotation.Resource),不需要导入格外的包,这个注解在JDK的rt.jar包中

  5. 可以标注的位置:TYPE(表示可以标注在接口、类、枚举),FIELD(变量域)和METHOD(方法)上面。

    1. @Target({TYPE, FIELD, METHOD})
    2. @Retention(RUNTIME)
    3. public @interface Resource {
    4. String name() default "";
    5. String lookup() default "";
    6. Class<?> type() default java.lang.Object.class;
    7. enum AuthenticationType {
    8. CONTAINER,
    9. APPLICATION
    10. }
    11. AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
    12. boolean shareable() default true;
    13. String mappedName() default "";
    14. String description() default "";
    15. }
  6. 在Spring容器解析@Resource注解时,使用的后置处理器为CommonAnnotationBeanPostProcessor,在这个后置处理的注释中有这么一段: ```java

  • {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
  • that supports common Java annotations out of the box, in particular the JSR-250
  • annotations in the {@code javax.annotation} package. These common Java
  • annotations are supported in many Java EE 5 technologies (e.g. JSF 1.2),
  • as well as in Java 6’s JAX-WS. *
  • This post-processor includes support for the {@link javax.annotation.PostConstruct}

  • and {@link javax.annotation.PreDestroy} annotations - as init annotation
  • and destroy annotation, respectively - through inheriting from
  • {@link InitDestroyAnnotationBeanPostProcessor} with pre-configured annotation types. *
  • The central element is the {@link javax.annotation.Resource} annotation

  • for annotation-driven injection of named beans, by default from the containing
  • Spring BeanFactory, with only {@code mappedName} references resolved in JNDI.
  • The {@link #setAlwaysUseJndiLookup “alwaysUseJndiLookup” flag} enforces JNDI lookups
  • equivalent to standard Java EE 5 resource injection for {@code name} references
  • and default names as well. The target beans can be simple POJOs, with no special
  • requirements other than the type having to match. ```
  1. 默认是按照组件名称进行装配的

为什么说@Autowired是根据类型,@Resource是根据组件名称,下面使用代码来进行解释:

  1. @Component
  2. public class Student {
  3. private String num = "1";
  4. public String getNum() {
  5. return num;
  6. }
  7. public void setNum(String num) {
  8. this.num = num;
  9. }
  10. }
  11. @Configuration
  12. @ComponentScan(basePackages = {"it.cast.autowired"})
  13. public class Config {
  14. @Bean
  15. public Student student1(){
  16. Student student = new Student();
  17. student.setNum("2");
  18. return student;
  19. }
  20. }
  21. @Component
  22. public class Teacher {
  23. @Resource //注意这里使用的@Resource注解,Spring支持注入Map、Conllent类型的属性变量
  24. private Map<String,Student> student;
  25. public Map<String, Student> getStudent() {
  26. return student;
  27. }
  28. public void setStudent(Map<String, Student> student) {
  29. this.student = student;
  30. }
  31. }
  32. public class Test01 {
  33. public static void main(String[] args) {
  34. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
  35. Teacher teacher = context.getBean(Teacher.class);
  36. System.out.println(teacher.getStudent());
  37. }
  38. }
  39. //打印结果:
  40. //Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'student' is expected to be of type 'java.util.Map' but was actually of type 'it.cast.autowired.Student'
  41. // at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:392)
  42. // at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
  43. // at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeanByName(AbstractAutowireCapableBeanFactory.java:452)
  44. // at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:527)
  45. // at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:497)
  46. // at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:637)
  47. // at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180)
  48. // at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
  49. // at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:322)
  50. // ... 12 more
  1. 可以看到使用@Resource标注的Map<String,Student>类型的时报错,为什么报错?因为Map类型的变量名为student,容器中已经存在了名称为student的bean,其类型为Student,所以会报错,大致步骤为:根据组件名称student去Spring容器中获取相应的Bean,在获取之后,会将获取到的Bean赋值给相应的属性。

如果此时将@Resource换成@Autowired时,其打印结果又会如何?

  1. @Component
  2. public class Student {
  3. private String num = "1";
  4. public String getNum() {
  5. return num;
  6. }
  7. public void setNum(String num) {
  8. this.num = num;
  9. }
  10. }
  11. @Configuration
  12. @ComponentScan(basePackages = {"it.cast.autowired"})
  13. public class Config {
  14. @Bean
  15. public Student student1(){
  16. Student student = new Student();
  17. student.setNum("2");
  18. return student;
  19. }
  20. }
  21. @Component
  22. public class Teacher {
  23. @Autowired //注意这里使用的@Autowired注解,Spring支持注入Map、Conllent类型的属性变量
  24. private Map<String,Student> student;
  25. public Map<String, Student> getStudent() {
  26. return student;
  27. }
  28. public void setStudent(Map<String, Student> student) {
  29. this.student = student;
  30. }
  31. }
  32. public class Test01 {
  33. public static void main(String[] args) {
  34. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
  35. Teacher teacher = context.getBean(Teacher.class);
  36. System.out.println(teacher.getStudent());
  37. }
  38. }
  39. //其打印结果:
  40. //{student=it.cast.autowired.Student@61009542, student1=it.cast.autowired.Student@77e9807f}

可以看到系统并没有报错,根据上面两组代码的对比,可以得出以下结论: :::success 当使用@Resource注解时,是根据组件名称进行查找,当使用@Autowired注解时,是根据类型进行查找的。 :::

  1. 支持@Primary注解,不过首先按照会按照名称进行注入bean,如果Spring IOC容器中没有该Bean,则按照@Primary注解标注的bean进行装配。

下面验证@Resource默认是按照组件名称进行装配的和持支@Primary注解的:

  1. @Configuration
  2. @ComponentScan({"it.cast.resouce"})
  3. public class ResourceConfig {
  4. @Primary //标有Primary注解,使用@Autowired@Inject注解注解时,优先被加载
  5. @Bean
  6. public Y y1(){
  7. Y y = new Y();
  8. y.setI(0);
  9. return y;
  10. }
  11. }
  12. @Component
  13. public class X {
  14. @Resource //这里使用的是@Resource注解,该注解默认按照组件名称进行装配的,所以会优先加载id为y的bean
  15. private Y y;
  16. public Y getY() {
  17. return y;
  18. }
  19. public void setY(Y y) {
  20. this.y = y;
  21. }
  22. }
  23. @Component
  24. public class Y {
  25. private int i = 2;
  26. public int getI() {
  27. return i;
  28. }
  29. public void setI(int i) {
  30. this.i = i;
  31. }
  32. }

测试一下使用@Resource注解的打印结果:

  1. @Test
  2. public void ResourceConfigTest(){
  3. AnnotationConfigApplicationContext context =
  4. new AnnotationConfigApplicationContext(ResourceConfig.class);
  5. X bean = context.getBean(X.class);
  6. System.out.println(bean.getY().getI());
  7. }
  8. //输出结果为:
  9. // 2
  10. //从而验证了@Resource默认按照名称进行加载

此时,将@Resource注解的属性名称换成y12,这个bean在容器里面没有的

  1. @Configuration
  2. @ComponentScan({"it.cast.resouce"})
  3. public class ResourceConfig {
  4. @Primary //标有Primary注解,使用@Autowired@Inject注解注解时,优先被加载
  5. @Bean
  6. public Y y1(){
  7. Y y = new Y();
  8. y.setI(0);
  9. return y;
  10. }
  11. }
  12. @Component
  13. public class X {
  14. @Resource //这里使用的是@Resource注解,该注解默认按照组件名称进行装配的,所以会优先加载id为y12的bean,
  15. private Y y12; //如果找不到则按Primary注解标注的bean进行注入
  16. public Y getY() {
  17. return y12;
  18. }
  19. public void setY(Y y) {
  20. this.y12 = y;
  21. }
  22. }
  23. @Component
  24. public class Y {
  25. private int i = 2;
  26. public int getI() {
  27. return i;
  28. }
  29. public void setI(int i) {
  30. this.i = i;
  31. }
  32. }

测试一下使用@Resource注解的打印结果:

  1. @Test
  2. public void ResourceConfigTest(){
  3. AnnotationConfigApplicationContext context =
  4. new AnnotationConfigApplicationContext(ResourceConfig.class);
  5. X bean = context.getBean(X.class);
  6. System.out.println(bean.getY().getI());
  7. }
  8. //输出结果为:
  9. // 0
  10. //由于没有找到id为y12的bean,所以注入了使用@Primary标注的bean,
  11. //而且整个程序没有报错,所以验证了@Resource支持@Primary注解

此时,将@Resource注解换成@Autowired注解的打印结果:

  1. @Configuration
  2. @ComponentScan({"it.cast.resouce"})
  3. public class ResourceConfig {
  4. @Primary //标有Primary注解,使用@Autowired@Inject注解注解时,优先被加载
  5. @Bean
  6. public Y y1(){
  7. Y y = new Y();
  8. y.setI(0);
  9. return y;
  10. }
  11. }
  12. @Component
  13. public class X {
  14. @Autowired
  15. private Y y; //此时不管名称是y还是y12,都会使用标有Primary注解的bean
  16. public Y getY() {
  17. return y;
  18. }
  19. public void setY(Y y) {
  20. this.y = y;
  21. }
  22. }
  23. @Component
  24. public class Y {
  25. private int i = 2;
  26. public int getI() {
  27. return i;
  28. }
  29. public void setI(int i) {
  30. this.i = i;
  31. }
  32. }

测试一下使用@Autowired注解的打印结果:

  1. @Test
  2. public void ResourceConfigTest(){
  3. AnnotationConfigApplicationContext context =
  4. new AnnotationConfigApplicationContext(ResourceConfig.class);
  5. X bean = context.getBean(X.class);
  6. System.out.println(bean.getY().getI());
  7. }
  8. //输出结果为:
  9. // 0
  10. //从而验证了@Autowired支持@Primary注解

@Inject

  1. JSR330规范提供的注解(javax.inject.Inject),主要导入javax.inject包才能使用
  2. 可以标注的位置:方法、构造器和变量域中

    1. @Target({ METHOD, CONSTRUCTOR, FIELD })
    2. @Retention(RUNTIME)
    3. @Documented
    4. public @interface Inject {} //该注解中没有任何属性
  3. 在Spring容器解析@Inject注解时,使用的后置处理器和@Autowired是一样的,都是AutowiredAnnotationBeanPostProcessor

  4. 由于@Inject注解没有属性,在加载所需bean失败时,会报错。 :::info 除了上面的不同点之后,**@Inject****@Autowired**完全等价。 :::