如何将 ToXmlGenerator.Feature 添加到 Jackson2ObjectMapperBuilderCustomizer?

How to add ToXmlGenerator.Feature to Jackson2ObjectMapperBuilderCustomizer?

我有下面的 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!

}

结果:

Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingJackson2XmlHttpMessageConverter' defined in class path resource [org/springframework/boot/autoconfigure/web/JacksonHttpMessageConvertersConfiguration$MappingJackson2XmlHttpMessageConverterConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter]: Factory method 'mappingJackson2XmlHttpMessageConverter' threw exception; nested exception is 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;
}

很接近,但是 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);
}