Skip to content

ServletContainerInitializer

ServletContainerInitializer is a mechanism introduced in Servlet 3.0 that allows third-party libraries or frameworks to programmatically register components like Filters, Servlets, and Listeners.^[600-developer-java-spring-servletcontainerinitializer.md] This approach enables initialization without requiring modifications to the project's web.xml file.^[600-developer-java-spring-servletcontainerinitializer.md]

Registration

To be discovered by the web container, an implementation of ServletContainerInitializer must be registered using the standard Java ServiceLoader mechanism.^[600-developer-java-spring-servletcontainerinitializer.md]

This requires a specific file to be included within the JAR file containing the implementation class^[600-developer-java-spring-servletcontainerinitializer.md]:

  • File Location: META-INF/services/javax.servlet.ServletContainerInitializer
  • File Content: The fully qualified class name of the implementation class (e.g., org.springframework.web.WebApplicationInitializer).^[600-developer-java-spring-servletcontainerinitializer.md]

Interface

The interface defines a single method, onStartup, which is called by the container during startup^[600-developer-java-spring-servletcontainerinitializer.md]:

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

Spring Implementation

The Spring Framework utilizes this mechanism through the class org.springframework.web.SpringServletContainerInitializer, which implements ServletContextInitializer^[600-developer-java-spring-servletcontainerinitializer.md]. This implementation typically leverages the @HandlesTypes annotation to identify specific initialization classes to process^[600-developer-java-spring-servletcontainerinitializer.md].

Sources

^[600-developer-java-spring-servletcontainerinitializer.md]