1. ApplicationContext 应用上下文获取方式
应用上下文对象是通过new ClasspathXmlApplicationContext(spring配置文件)方式获取的,但是每次从容器中获得Bean 时都要编写,这样的弊端是配置文件加载多次,应用上下文对象创建多次。
在Web项目中,可以使用ServletContextListener 监听Web 应用的启动,我们可以在Web 应用启动时,就加载Spring 的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext 域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext 对象了。
2. Spring 提供获取应用上下文的工具
上面的分析不用手动实现,Spring 提供了一个监听器ContextLoaderListener 就是对上述功能的封装,该监听器内部加载Spring 配置文件,创建应用上下文对象,并存储到ServletContext 域中,提供了一个客户端根据 WebApplicationContextUtils 供使用者获得应用上下文对象。
所以我们只需要做两件事:
(1)在web.xml 中配置ContextLoaderListener 监听器(导入spring-web 坐标)
(2)使用WebApplicationContextUtils 获得应用上下文对象ApplicationContext
3. 导入Spring 集成web 的坐标
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.5.RELEASE</version> </dependency>
4. 配置ContextLoaderListener 监听器
<!--全局参数--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--Spring的监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>