最近在研究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:指定要初始化的文件的位置。默認