休息模板 - XML缩进

时间:2017-03-20 16:53:47

标签: spring rest spring-boot jaxb spring-integration

在Spring Boot应用程序中使用Rest Template时,我需要使用新行和制表符缩进生成的XML。如何在此REST模板中设置JAXB Marshaller的缩进属性。

Spring REST模板代码:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);
    headers.add("Authorization", "Basic " +  Base64Utility.encode(userAndPass.getBytes()));

    Xml documentDefinition = myfactory.createObjects(StudentBean, ClassBean, CollegeBean);

   HttpEntity<Xml> request = new HttpEntity<>(documentDefinition, headers);

   URI result = restTemplate.postForLocation(builder.toUriString(), request);

Rest模板配置代码:

@Bean
@Qualifier("restTemp")
public RestTemplate restTemplate(RestTemplateBuilder builder,
                                 CloseableHttpClient httpClient) {
    return builder.requestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)).build();
}

2 个答案:

答案 0 :(得分:1)

您必须为RestTemplate bean注入Jaxb2RootElementHttpMessageConverter的扩展名。并实现其方法:

/**
 * Customize the {@link Marshaller} created by this
 * message converter before using it to write the object to the output.
 * @param marshaller the marshaller to customize
 * @since 4.0.3
 * @see #createMarshaller(Class)
 */
protected void customizeMarshaller(Marshaller marshaller) {
}

为此提供财产:

setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

答案 1 :(得分:0)

我通过以下方式注入Jaxbmarshaller解决了以下代码的问题:

@Bean
@Qualifier("restTemplate")
public RestTemplate restTemplate(RestTemplateBuilder builder,
                                 CloseableHttpClient httpClient) {
    RestTemplate restTemplate = builder.requestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)).build();

    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(getMarshallingHttpMessageConverter());
    converters.add(new Jaxb2RootElementHttpMessageConverter());
    converters.add(new MappingJackson2HttpMessageConverter());
    restTemplate.setMessageConverters(converters);
    return restTemplate;
}

@Bean(name = "marshallingHttpMessageConverter")
public MarshallingHttpMessageConverter getMarshallingHttpMessageConverter() {
    MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter();
    marshallingHttpMessageConverter.setMarshaller(getJaxb2Marshaller());
    marshallingHttpMessageConverter.setUnmarshaller(getJaxb2Marshaller());
    return marshallingHttpMessageConverter;
}

@Bean(name = "jaxb2Marshaller")
public Jaxb2Marshaller getJaxb2Marshaller() {
    Map<String, Object> props = new HashMap<>();
    props.put(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller.setClassesToBeBound(Xml.class);
    jaxb2Marshaller.setMarshallerProperties(props);
    return jaxb2Marshaller;
}