欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

@Autowired,@Inject,@Resource,@autowired@inject

来源: javaer 分享于  点击 30959 次 点评:93

@Autowired,@Inject,@Resource,@autowired@inject


Annotation Package Source
@Resource javax.annotation Java(JSR-250)
@Inject javax.inject Java(JSR-330)
@Qualifier javax.inject Java
@Autowired org.springframework.bean.factory Spring


The @Autowired and @Inject annotation behave identically. Both of these annotations use the AutowiredAnnotationBeanPostProcessor to inject dependencies. @Autowired and @Inject can be used interchangeable to inject Spring beans. However the @Resource annotation uses the CommonAnnotationBeanPostProcessor to inject dependencies.

@Autowired和@Inject注释的行为完全相同,均使用用AutowiredAnnotationBeanPostProcessor注入依赖项。而@Resource注释使用CommonAnnotationBeanPostProcessor进行注入,两者注释策略如下:

@Autowired and @Inject

  • Matches by Type
  • Restricts by Qualifiers
  • Matches by Name

@Resource

  • Matches by Name
  • Matches by Type
  • Restricts by Qualifiers (ignored if match is found by name)

@Autowired默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下:

    @Autowired
    @Qualifier("***")     
    private Bean bean;   

@Resource默认安照名称进行装配,名称可以通过name属性进行指定, 如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。name属性一旦指定,就只会按照名称进行装配。

  • Good practice would be to use @Inject instead of @Autowired because it is not Spring-specific and is part of the JSR-330 standard

  • Another good practice would be to put the @Inject / @Autowired on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException when you need to actually use the bean.
  • 好的做法是使用@Inject(非Spring特有的,而是JSR-330标准的一部分)而不是@Autowired。

  • 另一个好的实践是将@Inject/@Autowired注解在构造函数而不是方法上。这样可以快速验证注入Bean是否非空(程序启动时快速抛错),避免在需要实际使用bean时出现NullPointerException异常。

https://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/

https://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage

相关文章

    暂无相关文章
相关栏目:

用户点评