接上文spring集成web环境(手动实现)

##########代码接上文#############

spring提供了一个监听器ContextLoaderListener对上述功能的封装,该监听器内部加载spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获取上下文对象

1.导入spring-web坐标

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>

2.在web.xml中配置ContextLoaderListener监听器

<!--    配置监听器,spring-web提供的-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 全局初始化参数,告诉配置文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

3.使用WebApplicationContextUtils获取上下文对象ApplicationContext

public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save1();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}

4.启动服务器,访问userServlet
结果:sava running . . .