基于 Spring 的项目, 对象在 容器(container)中 生存. 容器负责:
容器是 Spring 的核心, Spring 的 容器 使用 DI 来管理各个应用程序的组件.
Spring 的容器有以下几种:
org.springframework.beans.factory.BeanFactory
接口, 定义了基本的 DI 功能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 创建的各个时机来 定制 bean.
BeanNameAware
接口, Spring 将会调用 setBeanName()
方法, 参数是 bean 的 ID. 可以让 Bean 直到自己的 名字.BeanFactoryAware
, Spring 将容器自身作为参数调用 setBeanFactory()
. 可以让 Bean 直到自己所在的工厂.ApplicationContextAware
, Spring 将会调用setApplicationContext()
方法, 参数是当前 applicationContext.BeanPostProcessor
, Spring 将会调用它 ProcessBeforeInitialization()
方法. InitializingBean
, Spring 将会调用它 afterPropertiesSet()
方法. Similarly, if the bean was declared with an init-method
, then the specified initialization method is called.BeanPostProcessor
, Spring 将会调用它的 postProcessAfterInitialization()
方法. DisposableBean
接口, Spring 将会调用它 destroy()
方法. Likewise, if the bean was declared with a destroy-method
, the specified method is called.原文:http://www.cnblogs.com/pragmatic/p/6360006.html