java.lang.IllegalStateException: Root context attribute is not of type WebApplicationContext
This error message plagued me for several hours. I don’t think I ever found a good answer, but I did find a way to get around it.
Here’s the situation: I developed a portlet for Liferay using Spring Portlet MVC and things went fine. Then I tried to develop another one and when I went to deploy, I got the dreaded exception. I still don’t understand the root of the problem, but I learned Spring has different types of application context objects: Web, Portlet, etc… It seemed like Spring was instantiating a portlet application context when it needed a web one.
The ContextLoaderListener will look for WEB-INF/applicationContext.xml. Define all your beans as usual in that file. Leave your portlet context file, but move all bean defs to the applicationContext.xml file. Just leave a stub in the portlet context file like this:
When you redeploy, you will see the following exception:
1234567
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:182)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at com.liferay.portal.spring.context.PortletContextLoaderListener.contextInitialized(PortletContextLoaderListener.java:78)
at com.liferay.portal.kernel.servlet.PortalClassLoaderServletContextListener.portalInit(PortalClassLoaderServletContextListener.java:90)
at com.liferay.portal.kernel.util.PortalInitableUtil.init(PortalInitableUtil.java:48)
...
This exception occurs because the web context is already established when Spring goes to create the portlet context. I haven’t found a way around this, but as long as you define all your beans in applicationContext.xml, things will work normally.