Spring注解驱动开发 第十三节 @Resource、@Inject 的使用与区别
除了@Autowired,还有@Resource(JSR250)、@Inject(JSR330),但是后两者不属于spring规范,而是从属于java规范,而@Autowired属于spring规范。
@Resource(name="bookDao")
private BookDao bookDao2;
表示装配名称为bookDao的组件。查看打印结果:
四月 24, 2019 3:43:53 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Wed Apr 24 15:43:53 GMT+08:00 2019]; root of context hierarchy
四月 24, 2019 3:43:53 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
BookService{bookDao=BookDao{label='1'}}
四月 24, 2019 3:43:53 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Wed Apr 24 15:43:53 GMT+08:00 2019]; root of context hierarchy
Process finished with exit code 0
可以看出组件名称为bookDao的被装配到属性中。
使用@Inject注解进行装配
首先用Inject进行装配要在引入一个依赖。下面是maven.pom文件的依赖坐标。
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
//@Autowired(required=false)
//@Qualifier("bookDao")
//@Resource(name="bookDao")
@Inject
private BookDao bookDao;
然后我们在用@Inject装配组件,查看打印结果:
四月 24, 2019 3:53:21 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Wed Apr 24 15:53:21 GMT+08:00 2019]; root of context hierarchy
四月 24, 2019 3:53:22 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
四月 24, 2019 3:53:22 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Wed Apr 24 15:53:21 GMT+08:00 2019]; root of context hierarchy
BookService{bookDao=BookDao{label='2'}}
Process finished with exit code 0
可以看到一样,名称为bookDao2的组件被装配到容器中。
总结:@Autowired、@Resource、@Inject都可以装配spring容器中的bean,但是他们三个有什么区别呢,我们对比一下。
首先用@Autowired和@Resource对比,首先autowired与resource的作用一样,都可以自动装配bean,但是他俩还是有很大的区别,autowired默认按照类型装配,而resource默认按照组件名称进行装配,第二resource没有@Primary与Autowired注解的reqiured属性功能。
最后对比一下@Auotwired与@Inject之间的区别,它们的区别只有一个就是它没有Autowired注解的reqiured属性功能,其他的都和Auotwired一样。虽然Autowired功能很全,但是它的作用范围只能在spring规范下,而resource与inject可以脱离spring。