Why this Spring application with java-based configuration don’t work properly

java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!

In your WebAppInitializer, you are registering a ContextLoaderListener.

Because you are using AbstractSecurityWebApplicationInitializer with the super constructor that accepts a Class[]

Creates a new instance that will instantiate the ContextLoaderListener with the specified classes.

that also registers a ContextLoaderListener. Note the class javadoc

When used with AbstractSecurityWebApplicationInitializer(Class...), it
will also register a ContextLoaderListener. When used with
AbstractSecurityWebApplicationInitializer(), this class is typically
used in addition to a subclass of AbstractContextLoaderInitializer.

As the error states, you cannot have two ContextLoaderListener instances because they will both try to create and add a ApplicationContext to the ServletContext.

Leave a Comment