Servlet 3.0 added a pluggability mechanism. How it works is that when your app is loaded, the Servlet container scans the classpath for a file named javax.servlet.ServletContainerInitializer
inside META-INF/services
. The contents of the file should simply be names of implementations of the initializer that the Servlet container can load. You can see this file in the spring-web
jar. It lists org.springframework.web.SpringServletContainerInitializer
as the implementation of the initializer.
How the Spring initializer works, is that it is passed all implementations (on the classpath) of WebApplicationInializer
by the Servlet container. So how does the Servlet container know to pass these implementations? If you look at the source code for the inializer, you will see
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
It is the @HandlesType
annotation. All classes and even annotations1 listed in the @HandlesTypes
will get picked up by the servlet container and passed to the SevletContainerInitializer
through the single callback method argument
void onStartup(java.util.Set<java.lang.Class<?>> c, ServletContext ctx)
The Set
argument contains all the implementations picked up by the Servlet container while scanning. You can look through the source code to see what Spring does with those implementations. It basically just calls the onStartup
of all the inializers, passing in the ServletContext
.
1. That sounded a bit unclear (and explaining it above would have been going a bit off on a tangent) so I'll just post it as an extra here. Imagine the @HandlesType
instead was
@HandlesTypes({WebApplicationInitializer.class, Controller.class})
public class SpringServletContainerInitializer implements ServletContainerInitializer {
This means that the servlet container will also scan for classes annotated with @Controller
, and also pass those onto the onStartup
of the Spring initializer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…