SpringMVC容器加载流程总结
流程图
流程
1.由于Servlet 3.0 的设计, 会自动扫描META-INF/services
下的javax.servlet.ServletContainerInitializer
实现。spring-web的实现是SpringServletContainerInitializer
。自定义META-INF/services
+实现ServletContainerInitializer
可以代替web.xml。
2.SpringServletContainerInitializer
关注所有WebApplicationInitializer
并调用其onStartup方法。
3.WebApplicationinitializer
有一个AbstractDispatcherServletInitializer
实现。发现其调用父类(AbstractContextLoaderInitializer
)的onStartUp
方法来创建Root WebApplicationContext
,和本类registerDispatcherServlet
来创建Servlet WebApplicationContext
。它是模板方法创建了两个容器,AbstractAnnotationConfigDispatcherServletInitializer
提供的抽象的实现,我们只需要定义@Configuration对应的类即可。
创建两个容器
两种容器
自定义WebApplicationInitializer
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}