简体   繁体   中英

How to force Jackson2ObjectMapperBuilder in spring-boot?

I want to create my own jackson ObjectMapper bean, as follows:

@SpringBootApplication
@AutoConfigureBefore(JacksonAutoConfiguration.class) //even this does not help
public class MyConfig extends SpringBootServletInitializer {
    @Bean
    @Primary
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        return builder.createXmlMapper(true).build(); //much more configurations
    }
}

Problem: the bean is never created, but instead the default JacksonAutoConfiguration is executed:

package org.springframework.boot.autoconfigure.jackson;

@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class JacksonAutoConfiguration {
        @Bean
        @Primary
        @ConditionalOnMissingBean(ObjectMapper.class)
        public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
            return builder.createXmlMapper(false).build(); //this is always executed!
        }
}

So somehow the ObjectMapper bean is not present yet when JacksonAutoConfiguration is evaluated. But why?

By debugging with breakpoints I can also see that my bean is never invoked! BUT what I noticed: even though I have the @AutoConfigureBefore , the jackson autoconfig is still run before any of the beans in MyConfig . Strange?

Here's Spring's documentation for customised ObjectMapper , this is what it says:

If you want to replace the default ObjectMapper completely, either define a @Bean of that type and mark it as @Primary , or, if you prefer the builder-based approach, define a Jackson2ObjectMapperBuilder @Bean . Note that in either case this will disable all auto-configuration of the ObjectMapper.

If defining ObjectMapper bean does not help, could you try defining Jackson2ObjectMapperBuilder bean instead?

Also, could you try defining the beans into a class annotated with @Configuration ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM