spring配置文件加载流程
转自:http://silmon.javaeye.com/blog/283515
Spring配置文件是集成了Spring框架的项目的核心,引擎从哪里开始,中间都执行了哪些操作,小谈一下它的执行流程。
容器先是加载web.xml
接着是applicationContext.xml在web.xml里的注册
一种方法是加入ContextLoaderServlet这个servlet
1 <context-param>
2 <param-name>contextConfigLocation</param-name>
3 <param-value>/WEB-INF/applicationContext.xml</param-value>
4 </context-param>
5 <servlet>
6 <servlet-name>context</servlet-name>
7 <servlet-class>
8 org.springframework.web.context.ContextLoaderServlet
9 </servlet-class>
10 <load-on-startup>0</load-on-startup>
11 </servlet>
2 <param-name>contextConfigLocation</param-name>
3 <param-value>/WEB-INF/applicationContext.xml</param-value>
4 </context-param>
5 <servlet>
6 <servlet-name>context</servlet-name>
7 <servlet-class>
8 org.springframework.web.context.ContextLoaderServlet
9 </servlet-class>
10 <load-on-startup>0</load-on-startup>
11 </servlet>
还有一种是添加ContextLoaderListener这个监听器
1 <context-param>
2 <param-name>contextConfigLocation</param-name>
3 <param-value>/WEB-INF/applicationContext.xml</param-value>
4 </context-param>
5
6 <listener>
7 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
8 </listener>
2 <param-name>contextConfigLocation</param-name>
3 <param-value>/WEB-INF/applicationContext.xml</param-value>
4 </context-param>
5
6 <listener>
7 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
8 </listener>
ContextLoaderServlet和ContextLoaderListener都是先创建ContextLoader的一个对象,然后调用它的initWebApplicationContex方法初始化WebApplicationContext获得一个对象;
spring加载多个配置文件,在web.xml中
1 <context-param>
2 <param-name>contextConfigLocation</param-name>
3 <param-value>classpath*:spring/*.xml</param-value>
4 </context-param>
5
6 <servlet>
7 <servlet-name>SpringContextServlet</servlet-name>
8 <servlet-class>
9 org.springframework.web.context.ContextLoaderServlet
10 </servlet-class>
11 <load-on-startup>3</load-on-startup>
12 </servlet>
2 <param-name>contextConfigLocation</param-name>
3 <param-value>classpath*:spring/*.xml</param-value>
4 </context-param>
5
6 <servlet>
7 <servlet-name>SpringContextServlet</servlet-name>
8 <servlet-class>
9 org.springframework.web.context.ContextLoaderServlet
10 </servlet-class>
11 <load-on-startup>3</load-on-startup>
12 </servlet>