分析Spring容器启动流程 Spring初始化
每当启动Web容器时(例如Tomcat),会读取Web应用中的web.xml文件。以下这段代码就是启动Spring容器的关键代码。
ContextLoaderListener 类继承了ContextLoader,实现 了ServletContextListener接口。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {public ContextLoaderListener() {}public ContextLoaderListener(WebApplicationContext context) {super(context);}public void contextInitialized(ServletContextEvent event) {this.initWebApplicationContext(event.getServletContext());}public void contextDestroyed(ServletContextEvent event) {this.closeWebApplicationContext(event.getServletContext());ContextCleanupListener.cleanupAttributes(event.getServletContext());}
}
ContextLoader:ContextLoaderListener可以指定在Web应用程序启动时载入Ioc容器,正是通过ContextLoader来实现的,ContextLoader来完成实际创建的WebApplicationContext,也就是Ioc容器的初始化工作。
ServletContextListener:负责监听ServletContext域的创建和销毁,当域创建时会调用contextInitialized方法(继承自ContextLoader)。创建WebApplicationContext(web应用上下文对象)并放入ServletContext域中以便调用。
这就是Spring容器的启动流程了。