内容简介:
虽然这一节的标题是Spring集成web环境,但讲的主要内容是ContextLoaderListener
还有通过配置Spring的ContextLoaderListener便捷地获取applicationContext的方法:
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
一、ContextLoaderListener的工作原理
在Spring项目中,用频繁用到Spring容器,也就是ApplicationContext对象,代码如下:
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
所以我们干脆把Spring容器放到全局唯一的servletContext对象中去,
写一个ContextLoaderListener实现ServletContextListenr接口
而ServletContextListenr会监听servletContext对象的创建,也就是服务器的启动
这样,ContextLoaderListner监听到服务器启动后就会自动加载Spring容器并存入servletContext对象中
另外,我们可以再写一个WebApplicationContextUtils类和getWebApplicationContext()方法
只需要传入servletContext对象就能返回applicationContext对象
最后,只需要去web.xml文件中配置好自己写的这个监听器就行了。。。。
二、Spring提供的官网接口
然而。。Spring其实已经帮我们封装好了上面这些,但是要导入spring-web坐标才能使用
代码如下:
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
三、如果你的项目是用xml配置文件,那么去web.xml中进行如下配置:
!--从类路径下加载Spring配置文件,classpath特指类路径下加载-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:smart-context.xml
</param-value>
</context-param>
<!--负责启动spring容器的监听器 还可以声明自启动的Servlet ContextLoaderServlet-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
四、如果你使用的是@Configuration注解配置类,那么使用这种方式配置:
<!--通过指定context参数,让Spring使用AnnotationConfigWebApplicationContext启动容器而非XmlWebApplicationContext 默认没配置时是使用XmlWebApplicationContext-->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<!--指定标注了@Configuration的类,多个可以用逗号分隔-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.example.Car,com.example.Boss</param-value>
</context-param>
<!--监听器将根据上面的配置使用AnnotationConfigWebApplicationContext
根据contextConfigLocation
指定的配置类启动Spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>