上一篇 <<<Web项目的启动方式汇总
下一篇 >>>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<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
List<WebApplicationInitializer> 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启动"部分内容。
推荐阅读:
<<<Spring Servlet相关知识
<<<Spring原理汇总及零碎知识点
<<<Web项目的启动方式汇总
<<<SpringMVC运行流程
<<<DispatcherServlet执行原理分析
<<<过滤器与拦截器的区别
<<<SpringMVC拦截器的用法
<<<SpringMVC异步实现方式
<<<@Async注解的失效之谜
<<<SpringMVC适配器类型汇总
网友评论