Spring - 1. 容器 和 Bean
Spring 容器
基于 Spring 的项目, 对象在 容器(container)中 生存. 容器负责:
- 对象的创建
- 对象的配置
- 对象的注入
- 对象生命周期管理
容器是 Spring 的核心, Spring 的 容器 使用 DI 来管理各个应用程序的组件.
Spring 的容器有以下几种:
- Bean factory, 实现了
org.springframework.beans.factory.BeanFactory
接口, 定义了基本的 DI 功能 - Application context, 继承自 bean factory 接口, 提供了应用层面的服务. 比如: 从 properties 文件中解析字符串.
Application Context
Application Context 有以下几种:
AnnotationConfigApplicationContext
, 从一个或多个 Java Config类 (@Configuration 标注的类) 中加载 application context.AnnotationConfigWebApplicationContext
, 从一个或多个 Java Config类中加载 Spring web applicationClassPathXmlApplicationContext
, 从一个或者多个在 classpath 中的 xml 文件加载 application context.FileSystemXmlApplicationContext
, 从一个或者多个文件系统中的 xml 文件中加载 application context.XmlWebApplicationContext
, 从 Web 应用中的一个或者多个 xml 文件加载 application context.
Spring bean 的声明周期
了解 Spring 的生命周期可以合理利用 bean 创建的各个时机来 定制 bean.
- Spring 实例化这个 bean.
- Spring 为 bean 的属性注入值和引用.
- 如果一个 bean 实现了
BeanNameAware
接口, Spring 将会调用setBeanName()
方法, 参数是 bean 的 ID. 可以让 Bean 直到自己的 名字. - 如果一个 bean 实现了
BeanFactoryAware
, Spring 将容器自身作为参数调用setBeanFactory()
. 可以让 Bean 直到自己所在的工厂. - 如果一个 bean 实现了
ApplicationContextAware
, Spring 将会调用setApplicationContext()
方法, 参数是当前 applicationContext. - 如果一个 bean 实现了
BeanPostProcessor
, Spring 将会调用它ProcessBeforeInitialization()
方法. - 如果一个 bean 实现了
InitializingBean
, Spring 将会调用它afterPropertiesSet()
方法. Similarly, if the bean was declared with aninit-method
, then the specified initialization method is called. - 如果一个 bean 实现了
BeanPostProcessor
, Spring 将会调用它的postProcessAfterInitialization()
方法. - 至此, 这个 bean 已经 被创建完成, 应用程序可以使用它, 直到 applicationContext 被销毁.
- 如果一个 bean 实现了
DisposableBean
接口, Spring 将会调用它destroy()
方法. Likewise, if the bean was declared with adestroy-method
, the specified method is called.