Spring集成Web环境
- 1.ApplicationContext应用上下文的获取
- [2. Spring提供获取应用上下文的工具](#2. Spring提供获取应用上下文的工具)
- 3.导入Spring集成web的坐标
- 4.配置ContextLoaderListener监听器
- 5.获取应用上下文对象
1.ApplicationContext应用上下文的获取
应用上下文对象是通过 new ClasspathXmlApplication(spring配置文件)方式获取,
每次从Spring容器中获取都要编写 new ClasspathXmlApplication这样会导致配置
文件加载多次,应用上下文对象创建多次。
Web项目中使用ServletContextListener 监听Web应用的启动,这样就可以在启动
Web项目时候就加载Spring的配置文件,创建应用上下文对象Application,并且将其
存储到最大域servletContext域中,这样就可以在任意位置从域中获得ApplicaitonContext
应用上下文对象。
2. Spring提供获取应用上下文的工具
Spring提供了一个监听器ContextLoadListener是对上述功能的封装,该监听器内部加载
Spring配置文件,创建应用上下文对象,并将其存储到ServletContext域中,还提供了一
个客户端工具WebApplicationContextUtils供使用者获取应用上下文对象
使用步骤:
- 在Web.xml中配置ContextLoaderListener监听器(导入spring-web)坐标
- 使用WebApplicaitonContextUtils获取应用上下文对象ApplicationContext
3.导入Spring集成web的坐标
xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
4.配置ContextLoaderListener监听器
xml
<!--全局参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--Spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
5.获取应用上下文对象
java
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
Object obj = applicationContext.getBean("id");