Spring——集成Web环境
简介
Spring集合Web环境:通过Listener自动创建ApplicationContext,并放入ServletContext中。通过这样不用每次都new ApplicationContext()
操作
1. web.xml中配置ContextLoaderListener监听器,监听Web启动
<!-- 全局初始化参数:让监听器从配置的路径中取得applicationContext.xml -->
<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
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
使用
<!-- 全局初始化参数:让监听器从配置的路径中取得applicationContext.xml --> <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>
@WebServlet(value = "/userController") public class UserController extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()); } }