gpt4 book ai didi

java - 如何在 spring-boot 中强制 Jackson2ObjectMapperBuilder?

转载 作者:行者123 更新时间:2023-11-30 02:23:11 25 4
gpt4 key购买 nike

我想创建自己的 jackson ObjectMapper bean,如下所示:

@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
}
}

问题:bean 从未创建,而是执行默认的 JacksonAutoConfiguration:

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!
}
}

因此,当评估 JacksonAutoConfiguration 时,ObjectMapper bean 还不存在。但为什么呢?

通过使用断点进行调试,我还可以看到我的 bean 从未被调用!但我注意到:即使我有@AutoConfigureBefore,jackson autoconfig仍然在MyConfig中的任何bean之前运行。奇怪吗?

最佳答案

Here's Spring关于定制ObjectMapper的文档,是这样说的:

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.

如果定义 ObjectMapper bean 没有帮助,您可以尝试定义 Jackson2ObjectMapperBuilder bean 吗?

另外,您可以尝试将 bean 定义到用 @Configuration 注释的类中吗?

关于java - 如何在 spring-boot 中强制 Jackson2ObjectMapperBuilder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46295337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com