Spring mvc:SpringServletContainerInitializer

SpringServletContainerInitializer实现了Servlet3.0规范中定义的ServletContainerInitializer:

public interface ServletContainerInitializer {
    void onStartup(Set> c, ServletContext ctx) throws ServletException;
}

SpringServletContainerInitializer代码如下:

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


	@Override
	public void onStartup(@Nullable Set> webAppInitializerClasses, ServletContext servletContext)
			throws ServletException {

		List initializers = Collections.emptyList();

		if (webAppInitializerClasses != null) {
			initializers = new ArrayList<>(webAppInitializerClasses.size());
			for (Class waiClass : webAppInitializerClasses) {
				// Be defensive: Some servlet containers provide us with invalid classes,
				// no matter what @HandlesTypes says...
				if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
						WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
					try {
						initializers.add((WebApplicationInitializer)
								ReflectionUtils.accessibleConstructor(waiClass).newInstance());
					}
					catch (Throwable ex) {
						throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
					}
				}
			}
		}

		if (initializers.isEmpty()) {
			servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
			return;
		}

		servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
		AnnotationAwareOrderComparator.sort(initializers);
		for (WebApplicationInitializer initializer : initializers) {
			initializer.onStartup(servletContext);
		}
	}

}

因为它使用了@HandlesTypes(WebApplicationInitializer.class)注解,所以web容器会寻找类路径上实现了WebApplicationInitializer的类。

它在onStartup方法中会分别调用WebApplicationInitializer的onStartup方法。

SpringServletContainerInitializer的onStartup方法会被支持Servlet3.0规范的web 容器(比如tomcat 9)自动调用

Spring-web模块的META-INFO目录的services目录下有名为javax.servlet.ServletContainerInitializer的文件,内容是

org.springframework.web.SpringServletContainerInitializer

可见,SpringServletContainerInitializer是通过SPI机制加载的。

你可能感兴趣的:(Spring,spring,mvc,java)