Spring的Ioc容器
第六章Spring Ioc容器之扩展篇
基于注解的依赖注入
自动绑定(@Autowired)
-
让容器知道需要为当前哪些类注入哪些依赖
-
byType按照类型匹配进行依赖注入
-
可以标注的位置
域/属性
构造方法定义
方法定义
-
需要在Ioc容器(ApplicationContext)中追加AutowiredAnnotationBeanPostProcessor
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
@Qualifier
- byName自动绑定注解版
- 和@Autowired搭配使用
使用JSR250标注依赖注入关系
-
@Resource @PostConstruct @PreDestroy
-
@Resource遵循byName自动绑定
-
@PostConstruct @PreDestroy不是用于依赖注入,主要用于标注对象生命周期管理相关方法
如果想某个方法在对象实例化之后被调用 或者想在对象销毁之前调用某个方法清理某些资源可调用这两个注解
-
JSR250注解需要一个beanPostProcessor
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
context:annotation-config/
会帮我们把AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor注册到容器中(即容器无需再引入前三个介绍的注解所对应的bean)
classpath-scanning功能介绍
- 功能触发由context:component-scan决定
- 默认扫描的注解类型是@Component
- 还扫描@Respository @Service @Controller
- 同时将AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor注入到了容器中