最近在研究IOC容器在web容器中初始化的过程。阅读了源码,参照了不少文章,在这里记录一下。
使用的web容器为tomcat7.spring的jar包为4.3.7.RELEASE版本。
咱们能够经过web.xml配置文件web容器中声明spring容器。有如下两种方式:
1:经过配置监听器来实现
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2:经过配置servlet来实现
因为web容器再启动时优先先扫描<listener>与<context-param>两个标签,因此推荐经过配置监听器的方式实现。
下面是经过配置监听器实现ioc容器在web容器中注册的方式。
Spring提供了ServletContextListener接口,以及他的实现类ContextLoaderListener。
它实现了建立初始化ServletContext后的事件监听和销毁ServletContext前的事件监听。
下面是web.xml中的代码
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>ffback</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/ApplicationContext1.xml,
classpath:spring/ApplicationContext2.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>标签用与配置ServletContext的参数。
咱们配置了webAppRootKey和contextConfigLocation两个参数。
webAppRootKey:web项目的绝对路径。同一个web容器中,不一样的项目要有不一样的webAppRootKey。
contextConfigLocation:指定要初始化的文件的位置。默认