Spring 3.2 content negotiation class cast exception

otter606 picture otter606 · Jan 31, 2013 · Viewed 14.5k times · Source

We develop a standard Java web application using Spring MVC, and have recently tried to upgrade from 3.0.6 to 3.2.0. Nearly of all our servlet responses are JSP or Json views, but there are some that are pdf requests, with extension 'pdf'.

In Spring 3.0.6 we had this set up, taken from the Spring MVC documentation.

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
  <entry key="pdf" value="application/pdf"/>
  <entry key="html" value="text/html"/>
  <entry key="json" value="application/json"/>
</map>

which worked fine, in combination with an XMLViewResolver.

After updating to 3.2.0, there is a failure :

Error creating bean with name' org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in class path  resource [dispatcher-test-servlet.xml]: Invocation of init method failed; nested exception is 

java.lang.ClassCastException: java.lang.String cannot be cast to                   org.springframework.http.MediaType'

After investigating the docs and some blogs, this configuration seems to work:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
   <property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
    <list>
    <!-- These are evaluated in order -->
    <!-- Is there a media type based on suffix? -->
<bean                  class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
    <map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="pdf" value="application/pdf" />
</map>
</constructor-arg>
</bean>
<!-- Else use request header -->
<bean
            class="org.springframework.web.accept.HeaderContentNegotiationStrategy">

</bean>
</list>
</constructor-arg>
</bean>
</property>

But, we have tried running the new Spring MVC test framework using this configuration, and get the ClassCast exception again, so it seems the test framework is not initialising the beans in the same way as when the application runs... Does anyone have a clear explanation of how to configure the ContentNegotiatingViewResolver in Spring 3,2 in a robust fashion? Thanks

Richard

Answer

Oleksii Kyslytsyn picture Oleksii Kyslytsyn · Aug 18, 2015

I fixed the problem by removing duplicated <mvc:annotation-driven/> from xml-configuration or @EnableWebMVC annotation from the class because spring documentation warns about that and allowed only once by contract.