也就是说, 以前的分析不用手动实现, Spring提供了一个监听器, 叫做ContextLoaderListener就是对上述功能的封装, 该监听器内部加载Spring配置文件, 创建应用上下文对象, 并存放到ServletContext域中, 提供了一个客户端工具, 叫做WebApplicationContextUtils供使用者获得上下文对象
我们要做两件事:
在web.xml中配置ContextLoaderListener(导入spring-web的jar包)
使用WebApplicationContextUtils获取app对象
<dependency>
<!--spring集成web环境的jar包-->
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--全局初始化变量-->
<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>
</web-app>
很明显, 在web.xml中的这个操作是使用spring-web这个jar包的关键(使用spring集成的监听器)
记得两个词
一个是ContextLoaderListener, 监听器的名称
一个是contextConfigLocation, 监听器使用的变量名称
@WebServlet("/saveUserServlet")
public class SaveUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = req.getServletContext();
//ApplicationContext app = (ApplicationContext)servletContext.getAttribute("app");
//使用这个工具类就可以完全忽略域中app的键名
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = (UserService)app.getBean("userService");
userService.save();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
为了隐藏键名写了一个getWebApplicationContext(servletContext)方法