February 26, 2015

AbstractAnnotationConfigDispatcherServletInitializer conflict with web.xml for Spring Security


When we use Spring Security in our application, we  extend 
AbstractAnnotationConfigDispatcherServletInitializer 
to include our WebSecurityConfigurerAdapter implementation into the root context.


However this can throw the following error during application startup

"Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your webxml!"

One reason the above may happen is because we could be having the following snippet in our web.xml

<listener>
<listener-class> org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param> 

which already creates the root context for the Application from
/WEB-INF/applicationContext.xml.


Servlet 3.X specification allows us to do away with XML and create Java-based configuration. So we can comment the above snippet in web.xml and add the following method in our AbstractAnnotationConfigDispatcherServletInitializer subclass to remove the above error.


@Override
protected WebApplicationContext createRootApplicationContext() {
// TODO Auto-generated method stub
return new XmlWebApplicationContext();
}

The no-arg XmlWebApplicationContext instance uses
"/WEB-INF/applicationContext.xml" by default.