Spring RestTemplate忽略XML annoations(例如@XmlAttribute)?

时间:2017-09-14 15:20:20

标签: java spring spring-mvc jaxb jackson

我使用spring-web向网络服务发送POST个xml请求。但是我的Xml bean请求没有呈现我使用jaxb属性定义它的方式:

//this class is autogenerated with xsdtojava from *.xsd files
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "myRequest")
public class ServletRequest {
    @XmlAttribute(name = "age")
    private int age;
}

用法:

ServletRequest req = new ServletRequest();
req.setAge(20);

restTemplateBuilder.build().postForEntity(url, new HttpEntity<>(req), MyRsp.class);

发送的结果xml:

<ServletRequest>
    <age>20</age>
</ServletRequest>

问题:@XmlRootElement名称和@XmlAttribute注释似乎都被忽略了。为什么呢?

1 个答案:

答案 0 :(得分:0)

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.modules(new JaxbAnnotationModule());
        }
    };
}

甚至更短的java8:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson() {
    return (builder) -> builder.modules(new JaxbAnnotationModule());
}

从杰克逊2.9.0开始,这是杰克逊核心库的一部分。

之前,您必须添加:

  <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>2.8.x</version>
    </dependency>