Spring Boot自定义Jackson反序列化 非配置文件配置wrap-exceptions=false不生效
配置不生效原因
你手动声明的Jackson2ObjectMapperBuilder Bean没有接入Spring Boot的Jackson自动配置流程:Spring Boot启动时会自动注册全局使用的Jackson2ObjectMapperBuilder实例,你直接新建返回的Builder实例优先级低于自动配置的实例,不会被用来构建全局生效的ObjectMapper,对应的特性配置自然无法生效。
正确实现方案
推荐方案:使用官方扩展点定制
使用Spring Boot提供的Jackson2ObjectMapperBuilderCustomizer定制器完成配置,这种方式不会和默认自动配置冲突,会将你定义的特性合并到全局Jackson配置中,同时保留Spring Boot对Jackson的所有默认预配置(比如常用模块自动注册、日期格式默认配置等),兼容性最好,代码如下:
import com.fasterxml.jackson.databind.DeserializationFeature; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer disableJacksonWrapExceptionCustomizer() { // 配置效果等价于spring.jackson.deserialization.wrap-exceptions=false return builder -> builder.featuresToDisable(DeserializationFeature.WRAP_EXCEPTIONS); } }
可选方案:直接注册ObjectMapper实例
如果你需要完全掌控ObjectMapper的初始化流程,可以直接注册ObjectMapper类型的Bean,并添加@Primary注解让自定义实例优先被容器使用。注意这种方式会覆盖Spring Boot对Jackson的所有默认预配置,非特殊场景不推荐使用:
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; @Configuration public class JacksonConfig { @Bean @Primary public ObjectMapper customObjectMapper() { return Jackson2ObjectMapperBuilder.json() .featuresToDisable(DeserializationFeature.WRAP_EXCEPTIONS) .build(); } }
内容的提问来源于stack exchange,提问作者SpicySandwich
相关产品推荐
相关产品推荐

