您的位置:首页 > 移动开发 > WebAPP

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 配置文件的位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: