Spring与Web环境集成

本文最后更新于:2 年前

ApplicationContext应用上下文获取方式

应用上下文对象是通过new ClasspathXmlApplicationContext (spring配置文件) 方式获取的,但是每次从容器中获得Bean时都要编写 new ClasspathXmlApplicationContext (spring配置文件) ,这样的弊端是配置文件加载多次,应用上下文对象创建多次。

在Web项目中,可以使用 ServletContextListener 监听 Web 应用的启动,我们可以在Web应用启动时,就加载 Spring 的配置文件,创建应用上下文对象 ApplicationContext,在将其存储到最大的 servletContext 域中,这样就可以在任意位置从域中获得应用上下文 ApplicationContext 对象了。

将Spring的应用上下文对象存储到ServletContext域中

从域中获得应用上下文 ApplicationContext 对象

Spring提供获取应用上下文的工具

上面的分析不用手动实现,Spring 提供了一个监听器 ContextLoaderListener 就是对上述功能的封装,该监听器内部加载 Spring 配置文件,创建应用上下文对象,并存储到 ServletContext 域中,提供了一个客户端工具 WebApplicationContextUtils 供使用者获得应用上下文对象。

所以我们需要做的只有两件事:

  1. 在 web.xml 中配置 ContextLoaderListener 监听器(导入spring-web坐标)
  2. 使用 WebApplicationContextUtils 获得应用上下文对象 ApplicationContex

1. 导入Spring集成web的坐标

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

2. 配置ContextLoaderListener监听器

1
2
3
4
5
6
7
8
9
10
<!--全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

3. 通过工具获得应用上下文对象

1
2
3
4
5
6
7
8
9
10
public class UserServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}

访问/userServlet时调用save()方法打印


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!