Spring——集成Web环境()
简介
Spring集合Web环境:通过Listener自动创建ApplicationContext,并放入ServletContext中。通过这样不用每次都new ApplicationContext()
操作
1. web.xml中配置ContextLoaderListener监听器,监听Web启动
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
2.使用WebApplicationContextUtils获得应用上下文对象ApplicationContext
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
使用
<context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:applicationContext.xmlparam-value> context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-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()); } }