When running my webapp, I get the stacktrace listed below every other try. Note that there doesn't seem to be multiple ContextLoader definitions im web.xml as far as I can tell. Moreover, the app runs just fine the second/fourth/etc. time. This behaviour is much harder to debug than if it simply didn't work. Can anyone shed some light on this?
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!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:299)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4795)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5221)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:919)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1703)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
For anyone with a similar problem - turns out that spring-jersey used in the project was setting up its own context. My context and the spring-jersey one were initialized in random order apparently.
More info here:
https://java.net/jira/browse/JERSEY-2038
https://java.net/projects/jersey/lists/users/archive/2014-03/message/124
The suggested solution of adding:
servletContext.setInitParameter("contextConfigLocation", "<NONE>");
In WebAppInitializer implementation didn't work reliably due to initialization order. What solved the problem was adding its xml equivalent:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</context-param>
as the firt parameter in web.xml, ensuring that its set before the context is initialized.
Make sure that you are not doing this if you are using spring boot
container.addListener(new ContextLoaderListener(rootContext));
来源:https://stackoverflow.com/questions/33633098/java-lang-illegalstateexception-cannot-initialize-context-because-there-is-alre