首页 > 编程语言 > 详细

Spring - 1. 容器 和 Bean

时间:2017-02-01 15:36:01      阅读:232      评论:0      收藏:0      [点我收藏+]

Spring 容器

技术分享

 

基于 Spring 的项目, 对象在 容器(container)中 生存. 容器负责:

  1. 对象的创建
  2. 对象的配置
  3. 对象的注入
  4. 对象生命周期管理

容器是 Spring 的核心, Spring 的 容器 使用 DI 来管理各个应用程序的组件.

Spring 的容器有以下几种:

  1. Bean factory, 实现了 org.springframework.beans.factory.BeanFactory接口, 定义了基本的 DI 功能
  2. Application context, 继承自 bean factory 接口, 提供了应用层面的服务. 比如: 从 properties 文件中解析字符串.

Application Context

Application Context 有以下几种:

  1. AnnotationConfigApplicationContext, 从一个或多个 Java Config类 (@Configuration 标注的类) 中加载 application context. 
  2. AnnotationConfigWebApplicationContext, 从一个或多个 Java Config类中加载 Spring web application
  3. ClassPathXmlApplicationContext, 从一个或者多个在 classpath 中的 xml 文件加载 application context.
  4. FileSystemXmlApplicationContext, 从一个或者多个文件系统中的 xml 文件中加载 application context. 
  5. XmlWebApplicationContext, 从 Web 应用中的一个或者多个 xml 文件加载 application context. 

Spring bean 的声明周期

技术分享

 

 

了解 Spring 的生命周期可以合理利用 bean 创建的各个时机来 定制 bean.

  1. Spring 实例化这个 bean.
  2. Spring 为 bean 的属性注入值和引用.
  3. 如果一个 bean 实现了 BeanNameAware 接口, Spring 将会调用 setBeanName() 方法, 参数是 bean 的 ID. 可以让 Bean 直到自己的 名字.
  4. 如果一个 bean 实现了 BeanFactoryAware, Spring 将容器自身作为参数调用 setBeanFactory(). 可以让 Bean 直到自己所在的工厂.
  5. 如果一个 bean 实现了 ApplicationContextAware, Spring 将会调用setApplicationContext() 方法, 参数是当前 applicationContext.
  6. 如果一个 bean 实现了 BeanPostProcessor, Spring 将会调用它 ProcessBeforeInitialization()方法. 
  7. 如果一个 bean 实现了 InitializingBean, Spring 将会调用它 afterPropertiesSet() 方法. Similarly, if the bean was declared with an init-method, then the specified initialization method is called.
  8. 如果一个 bean 实现了 BeanPostProcessor, Spring 将会调用它的 postProcessAfterInitialization() 方法. 
  9. 至此, 这个 bean 已经 被创建完成, 应用程序可以使用它, 直到 applicationContext 被销毁.
  10. 如果一个 bean 实现了 DisposableBean 接口, Spring 将会调用它 destroy() 方法. Likewise, if the bean was declared with a destroy-method, the specified method is called.

Spring - 1. 容器 和 Bean

原文:http://www.cnblogs.com/pragmatic/p/6360006.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!