Spring MVC 5中的默认消息转换器

时间:2018-03-07 12:03:19

标签: java json spring spring-mvc converters

我正在尝试理解为什么我的spring v.5.0.4-RELEASE无法正确加载默认的邮件转换器。 我从servlet.xml中删除了所有声明,我希望在spring中找到从AbstractMEssageConverterMethodProcessor正确加载的所有默认转换器,但我只得到以下4:

org.springframework.http.converter.ByteArrayHttpMessageConverter@35ca138b
org.springframework.http.converter.StringHttpMessageConverter@2b755f0d
org.springframework.http.converter.xml.SourceHttpMessageConverter@74f5d717
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@6982b849

有任何线索吗?

1 个答案:

答案 0 :(得分:2)

我最终了解问题是由RequestMappingHandlerAdapter bean

引起的
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

这覆盖了Spring默认值并发布了我的问题中列出的四个转换器。 解决方案是放置我正在寻找的转换器,如下所示:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean
                        class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="autoDetectFields" value="true" />
                        <property name="autoDetectGettersSetters" value="false" />
                        <property name="objectMapper">
                            <bean class="com.mypackage.CustomMapper" />
                        </property>
                    </bean>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"> 
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html</value>
                     </list>
                </property>
            </bean>
        </list>
    </property>
</bean>

完全忽略annotation-driven下的配置:

<mvc:annotation-driven>
    <mvc:message-converters>
    ...
    </mvc:message-converters>
</mvc:annotation-driven>