Spring Jaxb2RootElementHttpMessageConverter 不适用于 jaxb 注释

Posted

技术标签:

【中文标题】Spring Jaxb2RootElementHttpMessageConverter 不适用于 jaxb 注释【英文标题】:Spring Jaxb2RootElementHttpMessageConverter not working with jaxb annotations 【发布时间】:2016-05-01 22:28:28 【问题描述】:

我已经设置了使用:Jaxb2RootElementHttpMessageConverter 作为将对象转换为 xml 的消息转换器。在我的休息服务中,当生成响应时,它不遵守我在模型类上提供的 JAXB 注释。 :

基本响应:

@XmlRootElement(name="response")
@XmlSeeAlso(AddMemberResponse.class,UpdateMemberResponse.class)
public abstract class BaseResponse 


    private int status;
    private String message;
    private String confirmationCode;

    public String getMessage() 
        return message;
    
    public void setMessage(String message) 
        this.message = message;
    
    public int getStatus() 
        return status;
    
    public void setStatus(int httpInternalError) 
        this.status = httpInternalError;
    
    public String getConfirmationCode() 
        return confirmationCode;
    
    public void setConfirmationCode(String confirmationCode) 
        this.confirmationCode = confirmationCode;
    

AddMemberResponse:

@XmlRootElement(name = "response")
@XmlAccessorType(XmlAccessType.FIELD)
public class AddMemberResponse extends BaseResponse 

    private Member member;

    public AddMemberResponse() 
        super();
    

    public Member getMember() 
        return member;
    

    public void setMember(Member member) 
        this.member = member;
    

在我的代码中,我必须将 xml 保存到数据库中,因此我必须手动将其转换为 String 以便稍后保存,为此我使用 JaxbMarshaller 类,这工作正常:

/**
 * Converts object to xml using jaxb marshaller
 */
private String objectToXML(Object graph) throws IOException 

    String finalstring = null;
    try 

        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setPackagesToScan("com.company.ws");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jaxb.formatted.output", true);
        marshaller.setMarshallerProperties(map);

        // create a StringWriter for the output
        StringWriter outWriter = new StringWriter();
        StreamResult result = new StreamResult(outWriter);
        marshaller.marshal(graph, result);

        StringBuffer sb = outWriter.getBuffer();
        finalstring = sb.toString();
        log.debug(finalstring);

     catch(Exception e) 
        e.printStackTrace();
    
    return finalstring;

它使用 jaxbmarshaller 将其存储在数据库中,如下所示:

<response>
    <status>500</status>
</response> 

但它在 POSTMAN 中将其作为响应返回:

<AddMemberResponse>
    <status>500</status>
    <message/>
    <confirmationCode>UVHRWLHB6UMQ</confirmationCode>
    <member/>
</AddMemberResponse>

500是因为无法连接到外部服务获取数据,所以不相关,应该还是按照描述的方式返回。

配置了消息转换器的app-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Enables the Spring4 @Controller  -->
    <mvc:annotation-driven />

    <!-- To  convert JSON to Object and vice versa -->
    <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </bean> 

     <!-- To  convert XML to Object and vice versa -->
    <bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter">
    </bean> 


<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
            <ref bean="xmlMessageConverter"/>
        </list>
    </property> 
</bean>     
    <!-- Dozer configuration -->
    <bean id="beanMapper" class="org.dozer.DozerBeanMapper">
      <property name="mappingFiles">
        <list>
          <value>dozerMapping.xml</value>
        </list>
      </property>
    </bean>


    <context:component-scan base-package="com.company" />

</beans>

更新1:

as "application/xml" using [org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter@3f767117]

显示在日志中,因此在编组响应时未使用正确的转换器。

【问题讨论】:

【参考方案1】:

我必须删除对类路径的杰克逊依赖:

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-xml-provider</artifactId>
    <version>2.4.3</version>
</dependency>

MappingJackson2XmlHttpMessageConverter@3f767117 优先于 jaxb 转换器,如果它位于类路径中,因此编组是由该转换器完成的,而不是我的 jaxb 转换器。

【讨论】:

以上是关于Spring Jaxb2RootElementHttpMessageConverter 不适用于 jaxb 注释的主要内容,如果未能解决你的问题,请参考以下文章

Spring全家桶笔记:Spring+Spring Boot+Spring Cloud+Spring MVC

学习笔记——Spring简介;Spring搭建步骤;Spring的特性;Spring中getBean三种方式;Spring中的标签

Spring--Spring入门

Spring框架--Spring事务管理和Spring事务传播行为

Spring框架--Spring事务管理和Spring事务传播行为

Spring框架--Spring JDBC