前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >9-Spring集成web环境

9-Spring集成web环境

作者头像
Ywrby
发布2022-10-27 13:25:22
2730
发布2022-10-27 13:25:22
举报
文章被收录于专栏:YwrbyYwrby

ApplicationContext应用上下问的获取方式

下面是之前一直采用的应用上下问的获取方法

代码语言:javascript
复制
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service= (UserService) context.getBean("userService");
        service.save();
    }
}

通过new ClassPathXmlApplicationContext(“applicationContext.xml”)来获取应用上下文,不过这种方式获取的弊端就是所有web层的服务使用前都需要利用new ClassPathXmlApplicationContext(“applicationContext.xml”);加载配置文件,导致配置文件需要重复被加载多次,应用上下文的对象也需要创建多次

在Web项目中,要解决这个问题,可以利用ServletContextListener监听web应用的启动,一旦web应用启动,就加载Spring配置文件,并创建ApplicationContext应用上下文对象,然后将其存储入最大的域servletContext中,其他web层方法就可以在需要时直接从域中获取应用上下文对象

配置文件web.xml 配置监听器和Servlet

这里将Spring配置文件的文件名作为全局参数进行配置,避免了文件名加载配置文件导致的耦合

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--全局初始化参数 将Spring配置文件作为参数存储以解耦合-->
    <context-param>
        <param-name>applicationContext</param-name>
        <param-value>applicationContext.xml</param-value>
    </context-param>

    <!--配置监听器-->
    <listener>
        <listener-class>cn.ywrby.listener.ContextLoaderListener</listener-class>
    </listener>

    <!--配置Servlet-->
    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>cn.ywrby.web.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
    </servlet-mapping>
    

</web-app>
创建监听器
代码语言:javascript
复制
/**
 * 创建监听器,监听服务器启动
 */
public class ContextLoaderListener implements ServletContextListener {
    /**
     * 在服务器启动时加载配置文件创建应用上下文对象
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //获取ServletContext域
        ServletContext servletContext=sce.getServletContext();
        //从ServletContext域中获取全局初始化参数(获得Spring配置文件名)
        String context_name=servletContext.getInitParameter("applicationContext");
        //加载Spring配置文件并创建Spring应用上下文
        ApplicationContext context=new ClassPathXmlApplicationContext(context_name);
        //将Spring应用上下文存储到最大的域servletContext中
        servletContext.setAttribute("app",context);

    }
}
修改Servlet,从ServletContext域中获取Spring应用上下文
代码语言:javascript
复制
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //利用req从ServletContext域中获取存储的应用上下文对象
        ApplicationContext context= (ApplicationContext) req.getServletContext().getAttribute("app");
        //利用应用上下文获取Spring容器中的service层对象
        UserService service= (UserService) context.getBean("userService");
        service.save();
    }
}

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

上文提到的获取应用上下文的方式较为繁琐,并且每个web项目几乎都需要进行配置上下文的获取,所以Spring已经对应用上下文的获取进行了封装,我们只需要使用其提供的工具即可

Spring提供了一个监听器ContextLoaderListener就是对上述监听器的封装,该监听器实现了内部加载配置文件,创建应用上下文对象,并将对象存储在ServletContext域中,,同时提供了一个工具类WebApplicationContextUtils用来进行应用上下文的获取

使用步骤

0. 在pom.xml中导入spring-web坐标
代码语言:javascript
复制
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.3.3</version>
</dependency>
1. 在web.xml中配置ContextLoaderListener监听器

注意,这里的初始化参数名称必须是contextConfigLocation不能进行修改

代码语言:javascript
复制
<!--全局初始化参数 将Spring配置文件作为参数存储以解耦合-->
<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>
2. 使用WebApplicationContextUtils获取应用上下文对象ApplicationContext
代码语言:javascript
复制
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //(利用req获取ServletContext域)
        ServletContext servletContext=req.getServletContext();
        //利用WebApplicationContextUtils获取应用上下文
        WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //利用应用上下文获取Spring容器中的service层对象
        UserService service= (UserService) context.getBean("userService");
        service.save();
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-03-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ApplicationContext应用上下问的获取方式
    • 配置文件web.xml 配置监听器和Servlet
      • 创建监听器
        • 修改Servlet,从ServletContext域中获取Spring应用上下文
        • Spring提供的获取应用上下文的工具
          • 使用步骤
            • 0. 在pom.xml中导入spring-web坐标
            • 1. 在web.xml中配置ContextLoaderListener监听器
            • 2. 使用WebApplicationContextUtils获取应用上下文对象ApplicationContext
        相关产品与服务
        对象存储
        对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档