1

我有jackson下面的bean配置。如何将ToXmlGenerator.Feature.WRITE_XML_DECLARATION功能添加到构建器?

以下不起作用:

@Bean
public Jackson2ObjectMapperBuilderCustomizer initJackson() {
    return (builder) -> builder.modules(new JaxbAnnotationModule())
                .defaultUseWrapper(false)   
                .featuresToEnable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION); //invalid!

}

结果:

构造函数抛出异常;嵌套异常是 org.springframework.beans.factory.BeanCreationException:在类路径资源 [org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration$MappingJackson2XmlHttpMessageConverterConfiguration.class] 中定义名称为“mappingJackson2XmlHttpMessageConverter”的 bean 创建错误:通过工厂方法进行 Bean 实例化失败; 嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 [org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter]:工厂方法“mappingJackson2XmlHttpMessageConverter”抛出异常;嵌套异常是 org.springframework.beans.FatalBeanException: Unknown feature class: com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator$Feature

我最初的目标是在反序列化期间添加以下行:

<?xml version="1.0" encoding="UTF-8"?>.

也许有一种不同的方式而不是使用ToXmlGenerator?

我也尝试了以下方法,但这也没有添加 xml 声明行:

@Bean
@Primary
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    XmlMapper mapper = (XmlMapper) builder
            .createXmlMapper(true)
            .build();

    mapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    return mapper;
}
4

1 回答 1

4

它很接近,但是ObjectMapper用于将 java bean 序列化为 xml 的用途不是问题。而是在Jackson2ObjectMapperBuilderCustomizer新的映射器中由 spring 自动配置创建。这必须被覆盖如下:

@Bean
public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(
        Jackson2ObjectMapperBuilder builder) {
    ObjectMapper mapper = builder.createXmlMapper(true).build();
    ((XmlMapper) mapper).enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);
    return new MappingJackson2XmlHttpMessageConverter(mapper);
}
于 2017-09-20T07:03:19.057 回答