Spring 3.2内容协商类强制转换异常
问题内容:
我们使用Spring MVC开发了标准的Java
Web应用程序,并且最近尝试将其从3.0.6升级到3.2.0。我们几乎所有的servlet响应都是JSP或Json视图,但也有一些pdf请求,扩展名为“
pdf”。
在Spring 3.0.6中,我们从Spring MVC文档中进行了此设置。
<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>
与XMLViewResolver结合使用,效果很好。
更新到3.2.0后,出现故障:
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'
在研究了文档和一些博客之后,此配置似乎可以工作:
<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>
但是,我们尝试使用此配置运行新的Spring
MVC测试框架,并再次获取ClassCast异常,因此看来该测试框架没有以与应用程序运行时相同的方式初始化Bean。明确说明如何以健壮的方式在Spring
3,2中配置ContentNegotiatingViewResolver?谢谢
理查德
问题答案:
对于Spring
3.2,最好使用来解决ContentNegotiationManager
。它为我工作。您可以使用静态字段org.springframework.http.MediaType.APPLICATION_JSON_VALUE
来提及媒体类型。检查以下代码:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json">
<util:constant static-field="org.springframework.http.MediaType.APPLICATION_JSON_VALUE" />
</entry>
<entry key="xml">
<util:constant static-field="org.springframework.http.MediaType.APPLICATION_XML_VALUE" />
</entry>
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
<property name="defaultViews">
<list>
<!-- default views -->
</list>
</property>
</bean>
为此,您必须在您的dispatcher-
servlet.xml文件中使用util模式,即xmlns:util="http://www.springframework.org/schema/util"
模式位置
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-
工具3.0.xsd