Spring学习之旅(二)--容器

Spring 应用中,所有的对象都在 Spring 容器(container) 里,容器负责对象的创建、配置、装配并管理它们的整个生命周期。

Spring 容器

Spring 容器 并不是只有一个, Spring 自带了多个容器的实现,可以归为两种不同的类型:

  • bean 工厂(org.springframework.beans.factory.BeanFactory)
  • 应用上下文(org.springframework.context.ApplicationContext)

虽然两者都可以使用,但是 bean 工厂 对大多数应用来说太低级了,因此我们通常会选择 应用上下文 的形式。

应用上下文

Spring 自带了多种类型的应用上下文:

类型 含义
AnnotationConfigApplicationContext 从一个或多个基于Java配置类中加载 Spring 应用上下文
AnnotationConfigWebApplicationContext 从一个或多个基于Java的配置类中加载Spring Web 应用上下文
ClassPathXmlApplicationContext 从类路径下的一个或多个XML配置文件中加载上下文定义,把应用上下文的定义文件作为类资源
FileSystemXmlapplicationcontext 从文件系统下的一个或多个XML配置文件中加载上下文定义
XmlWebApplicationContext 从Web应用下的一个或多个XML配置文件中加载上下文定义

获取上下文

从 Java 配置中加载:

ApplicationContext context = new AnnotationConfigApplicationContext("com.config.KnightConfig.class");

从文件路径中加载:

ApplicationContext context = new FileSystemXmlapplicationcontext("d:/applictionContext.xml");

从类路径中加载:

ApplicationContext context = new ClassPathXmlApplicationContext("applictionContext.xml");

获取 bean

UserService userService = context.getBean(UserService.class);

bean 的生命周期

  • Springbean 进行实例化;

  • Spring 将值和 bean 的引用注入到 bean 对应的属性中;

  • 如果 bean 实现了 BeanNameAware 接口,SpringbeanId 传递给 setBean-Name() 方法;

  • 如果 bean 实现了 BeanFactoryAware 接口,Spring 将调用 setApplicationContext() 方法,将 bean 所在的应用上下文的一引用传入进来;

  • 如果 bean 实现了 BeanPostProcessor 接口,Spring 将调用它们的 post-ProcessBeforeInitialization() 方法;

  • 如果 bean 实现了 InitializingBean 接口,Spring 将调用它们的 after-PropertiesSet() 方法,类似地,如果 bean 使用了 init-method 申明了初始化方法,此方法也会被调用;

  • 如果 bean 实现了 BeanPostProcessor 接口,Spring 将调用它们的 post-ProcessAfterInitialization() 方法;

  • bean 已经准备就绪,将一直驻留在应用上下文中,直到该应用上下文被销毁

  • 如果 bean 实现了 DisposableBean 接口,Spring 将调用它的 destroy 接口方法。如果 bean 使用了 destroy-methode 声明了销毁方法,该方法也会被调用

posted @ 2019-08-23 15:29  MarkLogZhu  阅读(177)  评论(0编辑  收藏  举报