SpringMVC底层无web.xml启动原理分析

上一篇 << 下一篇 >>>SpringMVC运行流程


1.按tomcat启动的格式,写好META-INF及文件名称

org.springframework.web.SpringServletContainerInitializer

2.所有实现了WebApplicationInitializer的接口都会自动加入到Set参数里,遍历调用具体的initializer.onStartup(servletContext);进行组件的初始化工作。

@HandlesTypes({WebApplicationInitializer.class})
public class SpringServletContainerInitializer implements ServletContainerInitializer {
    public SpringServletContainerInitializer() {
    }

    public void onStartup(@Nullable Set> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
        List initializers = new LinkedList();
        Iterator var4;
        if (webAppInitializerClasses != null) {
            var4 = webAppInitializerClasses.iterator();

            while(var4.hasNext()) {
                Class waiClass = (Class)var4.next();
                if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((WebApplicationInitializer)ReflectionUtils.accessibleConstructor(waiClass, new Class[0]).newInstance());
                    } catch (Throwable var7) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", var7);
                    }
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
        } else {
            servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
            AnnotationAwareOrderComparator.sort(initializers);
            var4 = initializers.iterator();

            while(var4.hasNext()) {
                // 调用实现WebApplicationInitializer接口的onStartup方法
                WebApplicationInitializer initializer = (WebApplicationInitializer)var4.next();
                initializer.onStartup(servletContext);
            }
        }
    }
}

3.利用类AnnotationConfigWebApplicationContext加载自定义的配置文件类MyConfig完成初始化动作。

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    public void onStartup(javax.servlet.ServletContext servletContext)  {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(MyConfig.class);
        ServletRegistration.Dynamic defaultServlet = servletContext.addServlet("defaultServlet", new DispatcherServlet(context));
        defaultServlet.addMapping("/");
        defaultServlet.setLoadOnStartup(1);
        defaultServlet.setAsyncSupported(true);
    }
}

MyConfig.class内容参考Web项目的启动方式汇总中"SpringMVC集成启动无web.xml启动"部分内容。


推荐阅读:
<< << << << << <<<过滤器与拦截器的区别
<< << <<<@Async注解的失效之谜
<<

你可能感兴趣的:(SpringMVC底层无web.xml启动原理分析)