web.xml中启用Spring
在一般的web应用程序,我们倘若用到Spring的话,需要在web.xml中配置以下的信息来使一些容器,例如Tomcat
、Jetty
等来加载Spring
<!-- Spring配置文件信息 -->
<context-param>
<!-- 这个contextConfigLocation参数是用来加载spring相关配置的标签 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/conf/applicationContext.xml</param-value>
</context-param>
<!-- ContextLoaderListener监听器 -->
<!-- ContextLoaderListener的作用就是启动Web容器时,自动装配
ApplicationContext.xml的配置信息
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Spring主要通过ContextLoaderListener
类在应用启动时加载其服务
ContextLoaderListener的官方注释
查看某个类的重要功能最好是观察其的注释,ContextLoaderLinstener
官方注释如下:
//父级启动类,可用ContextLoader启动和ContextCleanupListener来关闭Spring的根web应用上下文
Bootstrap listener to start up and shut down Spring's root {@link WebApplicationContext}.
Simply delegates to {@link ContextLoader} as well as to {@link ContextCleanupListener}.
//这里给出了提示,如果需要用到自定义log4j的配置的话,则ContextListener需要在Log4jConfigListener之后
<p>This listener should be registered after {@link org.springframework.web.util.Log4jConfigListener}
in {@code web.xml}, if the latter is used.
//从Spring3.1之后,注入根web应用上下文可通过 WebApplicationInitializer,容器在启动会加载此接口,但是有个要求是容器的Servlet版本必须是3.0+,对Tomcat来说必须是7.0.15版本以上
<p>As of Spring 3.1, {@code ContextLoaderListener} supports injecting the root web
application context via the {@link #ContextLoaderListener(WebApplicationContext)}
constructor, allowing for programmatic configuration in Servlet 3.0+ environments.
See {@link org.springframework.web.WebApplicationInitializer} for usage examples.
@author Juergen Hoeller
@author Chris Beams
@since 17.02.2003
@see #setContextInitializers
@see org.springframework.web.WebApplicationInitializer