@Autowired,@Inject,@Resource 刺骨的言语ヽ痛彻心扉 2022-06-05 08:45 169阅读 0赞 <table> <thead> <tr> <th>Annotation</th> <th>Package</th> <th>Source</th> </tr> </thead> <tbody> <tr> <td>@Resource</td> <td>javax.annotation</td> <td>Java(JSR-250)</td> </tr> <tr> <td>@Inject</td> <td>javax.inject</td> <td>Java(JSR-330)</td> </tr> <tr> <td>@Qualifier</td> <td>javax.inject</td> <td>Java</td> </tr> <tr> <td>@Autowired</td> <td>org.springframework.bean.factory</td> <td>Spring</td> </tr> </tbody> </table> > 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][Inject_Autowired]注解在构造函数而不是方法上。这样可以快速验证注入Bean是否非空(程序启动时快速抛错),避免在需要实际使用bean时出现NullPointerException异常。 [https://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/][https_blogs.sourceallies.com_2011_08_spring-injection-with-resource-and-autowired] [https://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage][https_stackoverflow.com_questions_19414734_understanding-spring-autowired-usage] [Inject_Autowired]: https://stackoverflow.com/questions/20485059/spring-boot-how-can-i-set-the-logging-level-with-application-properties [https_blogs.sourceallies.com_2011_08_spring-injection-with-resource-and-autowired]: https://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/ [https_stackoverflow.com_questions_19414734_understanding-spring-autowired-usage]: https://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage
还没有评论,来说两句吧...