每次请求都会创建一个新的容器,但是在web项目中我们只需要一个spring的容器。所以我们开始了“配置Spring随项目启动”:
每次请求都会创建一个新的容器,但是在web项目中我们只需要一个spring的容器。所以我们开始了“配置Spring随项目启动”:
解决web项目中只需要一个spring容器
利用ServletContextListener 通过配置监听器来打到我们的需求,在web项目创建时创建spring容器,销毁时候关闭spring容器
在web.xml中配置 监听器,
<!-- 配置监听器,在web项目启动的时候让spring启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener.class</listener-class>
</listener>
<!-- 读取spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
在UserLoginServlet中:
//ServletContextListener 可以通过配置监听器来打到我们的需求,在web项目创建时创建spring容器,销毁时候关闭spring容器
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
us = (UserService)wac.getBean("userService");