Spring集成web环境

举报
兮动人 发表于 2021/10/17 23:30:52 2021/10/17
【摘要】 Spring集成web环境

1. ApplicationContext应用上下文获取方式

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

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

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

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

  • 所以我们需要做的只有两件事:
    1、在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
    2、使用WebApplicationContextUtils获得应用上下文对象ApplicationContext

3. 案例测试

  • 先准备好 UserDao、UserDaoImpl、UserService、UserServiceImpl

  • 新建 Servlet 类 充当 web 层

  • UserDaoImpl
    在这里插入图片描述

  • UserServiceImpl
    在这里插入图片描述

  • 导入Spring集成web的坐标 和 Servlet 依赖

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
	<version>3.0.1</version>
	<scope>provided</scope>
</dependency>

<dependency>
	<groupId>javax.servlet.jsp</groupId>
	<artifactId>javax.servlet.jsp-api</artifactId>
	<version>2.2.1</version>
	<scope>provided</scope>
</dependency>

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>5.3.10</version>
</dependency>
  • 配置ContextLoaderListener监听器,在 web.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>

<servlet>
	<servlet-name>UserServlet</servlet-name>
	<servlet-class>com.xdr630.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>UserServlet</servlet-name>
	<url-pattern>/userServlet</url-pattern>
</servlet-mapping>

在这里插入图片描述

  • 新建 Servlet 类 充当 web 层,通过工具获得应用上下文对象
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();
    }
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。