Spring 学习笔记(2)—— ApplicationContext 及 WebApplicationContext 的初始化
2017-10-31 08:57
483 查看
前言
Spring 通过一个配置文件描述 Bean 和 Bean 之间的依赖关系,利用 Java 语言的反射功能实例化 Bean,并建立 Bean 之间的依赖关系。BeanFactory(com.springframework.beans.factory.BeanFactory)是 Spring 框架最核心的接口,提供了高级 IoC 的配置机制。BeanFactory 使管理不同类型的 Java 对象成为可能,
ApplicationContext(com.springframework.context.ApplicationContext)建立在 BeanFactory 之上。
一般称
BeanFactory为
IoC 容器,而称
ApplicationContext为
应用上下文。但有时为了行文方便,也称
ApplicationContext为
Spring 容器。
ApplicationContext 介绍
ApplicationContext的主要实现类是
ClassPathXmlApplicationContext和
FileSystemXmlApplicationContext,前者默认从类路径加载配置文件,后者默认从文件系统中加载配置文件。
ApplicationContext 的初始化 (基于 XML 文件的配置方式)
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
还可以指定一组配置文件, Spring 会自动将多个配置文件在内存中“整合”成一个配置文件
ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"classpath:applicationContext.xml", "classpath:bean.xml" });
除了可以采用
基于 XML 配置文件的方式启动 Spring 容器外,
还可以采用
以带有 @Configuration 的配置类启动容器,
以及
使用 Groovy-DSL 来进行 Bean 定义配置。
WebApplicationContext 介绍
WebApplicationContext是专门为 Web 应用准备的,它允许从相对于 Web 根目录的路径中装载配置文件完成初始化工作。
WebApplicationContext的初始化需要 ServletContext 实例,必须在拥有 Web 容器的前提下才能完成启动工作。可以在 web.xml 文件中配置自启动的 Servlet 或是定义 Web 容器监听器,就可以完成启动 Spring
WebApplicationContext的工作。
通过 Web 容器监听器引导
<!-- 加载spring容器 --> <!-- 指定配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath: applicationContext-*.xml</param-value> </context-param> <!-- 声明 Web 容器监听器 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
ContextLoaderListener 通过 Web 容器上下文参数 contextConfigLocation 获取 Spring 配置文件的位置。
相关文章推荐
- Spring学习笔记2——web项目初始化webapplicationcontext
- spring源码学习笔记-初始化(一)-概览
- spring: web学习笔记1--异常处理:No adapter for handler
- Spring MVC 学习笔记2 - 利用Spring Tool Suite创建一个web 项目
- spring源码学习笔记-初始化(三)-BeanFactory
- Spring 4 官方文档学习(十一)Web MVC 框架之编码式Servlet容器初始化
- spring源码学习笔记-初始化(五)-MessageSource/事件监听器
- Spring学习笔记 通过PropertyPlaceholderConfigurer来使用properties文件初始化Map类型属性
- Spring Web MVC 的学习笔记
- spring源码学习笔记-初始化(二)-BeanFactory
- Java for Web学习笔记(六四):Controller替代Servlet(6)Spring Form Tag
- Spring Web Flow 学习笔记(2)-流程的组件
- Spring学习历程---WebApplicationContext初始化
- spring源码学习笔记-初始化(六)-完成及异常处理
- Spring Boot 学习笔记(二)—— WEB相关配置
- vue学习笔记-----vue+webpack初始化项目(vue1.0的安装)
- Spring学习笔记之构建Spring Web应用程序
- spring源码学习笔记-初始化(二)-BeanFactory
- spring源码学习笔记-初始化(二)-BeanFactory
- Spring学习笔记 关于Bean的初始化和清理-init和destroy方法