Why Spring Security need a ContextLoaderListener

If you are using Spring Security, you need to configure a ContextLoaderListener, if you don't configure it properly, you get a error.

For basic MVC, the Dispatcher Servlet is enough. But the application context of Dispatcher Servlet is specifically for MVC. Beans in the context are controllers, viewers, handlers, etc.

But Spring Security is not part of the MVC, its an independent component, and it has its own beans need to be managed by Spring container. This is what the root application context for, created by ContextLoaderListener.

In Spring, you don't have to register ContextLoaderListener by yourself, there is an implementation existed to do this, you can simply extends the class and pass in the annotated security configuration class.

 
 
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
    public SecurityWebApplicationInitializer() {
        super(ExampleSecurityConfiguration.class);
    }
}