Spring集成web环境
标签(空格分隔): Spring
ApplicationContext应用上下文获取方式
应用上下文对象时通过newClasspathXmlApplicationContext(spring配置文件)方式获取的,但每次从容器中获得Bean时都要编写newClasspathXmlApplicationContext(spring配置文件),这样的弊端是配置文件加载多次,应用上下文对象创建多次
在web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了。
Spring提供获取应用上下文的工具
Spring提供了一个监听器ContextLoaderListener实现了对以下`功能`的封装,该监听器内部加载Spring配置文件,创建应用上下文对象考虑,并转存到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。
实现原理:
- 通过一个监听器Listener使得Web项目在启动时就直接在Context域中加载Spring容器,从而使得全局只加载一次,减少重复加载
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
//读取web.xml中的全局参数
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
//将Spring的应用上下文对象存储到ServletContext域中
servletContext.setAttribute("app",app);
System.out.println("spring容器创建完毕...");
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
- 在通过一个WebApplicationContextUtils来实现获得应用上下文对象,从而使得获取的实现不需要记住Attribute中的别名
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
return (ApplicationContext)servletContext.getAttribute("app");
}
}
所以我们需要做的只有两件事:
- 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
- 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext
Spring集成web环境步骤:
- 配置ContextLoaderlistener监听器
<!--全局初始化参数-->
<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>
- 使用WebApplicationContextUtils获得应用上下文
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
ServletContext servletContext = this.getServletContext();
WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}