IOC容器的创建就是我们创建一个容器,使其有IOC容器的基本结构,能够管理bean,定义读取等。
web容器的IOC容器创建使用createWebApplication()
函数完成IOC容器的创建。
IOC容器的创建是读取bean的定义,并加载入beanDefinition并注册到一个HashMap中。下文中的ConfigureAndRefreshWebApplicationContext()
进行IOC容器初始化工作。
//web.xml
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Spring/ApplicationContext.xml</param-value>
</init-param>
<listener>
<listener-class>org.springframework.web.content.ContextLoaderListener</listener-class>
</listener>
contextConfigLocation是Spring配置文件绝对路径
ContextLoaderListener是对Servlet容器(Tomcat)进行监听并执行
//ContextLoaderListener
public ContextLoaderListener(WebApplocationContext context){
super(context);
}
1. //这里对根上下文进行初始化。
2. public void contextInitialized(ServletContextEvent event) {
3. //这里创建需要的ContextLoader
4. this.contextLoader = createContextLoader();
5. //这里使用ContextLoader对上下文进行载入和初始化
6. this.contextLoader.initWebApplicationContext(event.getServletContext());
7. }
public void contextDestroyed(ServletContextEvent event){
//...
}
contextInitialized方法的入参或是监听的Event是ServletContextEvent事件,是Tomcat启动加载完web.xml会产生的事件,ServletContextEvent持有了从web.xml加载的初始化配置的ServletContext上下文。
流程:当Servlet容器启动事件发生时,将被ContextLoaderListen监听器监听到。此时ContextLoaderListener会调用实现ServletContextListener接口后实现的contextInitialized方法,并把在web.xml加载初始化后获取的ServletContext传入initWebApplicationContext函数中进行IoC容器的初始化。
initWebApplicationContext检查容器是否初始化,如果没有则调用createWebApplicationContext方法来创建一个容器然后调用configureAndRefreshWebApplicationContext完成配置文件放入xml上下文,并使用refresh完成容器初始化,然后将xml上下文注册到ServletContext。