ContextLoaderListener versus DispatcherServlet
The o.s.web.servlet.DispatcherServlet interface specifies configuration classes to be loaded on their own using the getServletConfigClasses() method:
//src/main/java/c/p/s/web/configuration/WebAppInitializer
public class WebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
...
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfig.class };
}
...
@Override
public void onStartup(final ServletContext servletContext) throws
ServletException {
// Registers DispatcherServlet
super.onStartup(servletContext);
}
}
The DispatcherServlet class creates o.s.context.ApplicationContext, which is a child of the root ApplicationContext interface. Typically, Spring MVC-specific components are initialized in the ApplicationContext interface of DispatcherServlet, while the rest are loaded by ContextLoaderListener. It is important to know that beans in a child ApplicationContext (such as those created by DispatcherServlet) can reference beans of the parent ApplicationContext (such as those created by ContextLoaderListener). However, the parent ApplicationContext interface cannot refer to beans of the child ApplicationContext.
This is illustrated in the following diagram, in which Child Beans can refer to Root Beans, but Root Beans cannot refer to Child Beans:
As in most use cases of Spring Security, we do not need Spring Security to refer to any of the MVC-declared beans. Therefore, we have decided to have ContextLoaderListener initialize all configurations of Spring Security.