在前面章节的介绍中,我们都是用ObjectMapper来做的测试,那么在SpringBoot(以下简称sb)中如何的对Jackson提供个性化的配置呢。
一般来说,在sb中,如果要激活某个组件,都会在spring-boot-autoconfigure中进行autoconfigure,果不其然,我们在其中发现了JacksonAutoConfiguration类,且其中有如下的代码
@Bean
@Primary
@ConditionalOnMissingBean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}
可以看到在这个configure类里面会生成一个Primary的ObjectMapper的bean(这就是我们为什么一直用ObjectMapper做序列化测试的原因),其依赖了Jackson2ObjectMapperBuilder的bean,而在此configure里面会找到如下的代码
@Configuration
@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
static class JacksonObjectMapperBuilderConfiguration {
private final ApplicationContext applicationContext;
JacksonObjectMapperBuilderConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
@ConditionalOnMissingBean
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.applicationContext(this.applicationContext);
customize(builder, customizers);
return builder;
}
private void customize(Jackson2ObjectMapperBuilder builder,
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) {
customizer.customize(builder);
}
}
}
此段代码会生成一个Jackson2ObjectMapperBuilder的bean,也就是我们上面生成ObjectMapper使用到的bean,而Jackson2ObjectMapperBuilder bean的生成又依赖了List<Jackson2ObjectMapperBuilderCustomizer> ,等于说sb会把容器里面的所有的Jackson2ObjectMapperBuilderCustomizer拿出来,统一对Jackson2ObjectMapperBuilder进行设置操作,也就间接的控制了ObjectMapper的生成,所以我们如果要对ObjectMapper做特殊的配置化操作的话,我们只需要实现Jackson2ObjectMapperBuilderCustomizer这个接口并注册这个实现的bean就可以了。
可以看到Jackson2ObjectMapperBuilderCustomizer只有一个方法,void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder);
其实就是Jackson2ObjectMapperBuilder提供给用户的回调钩子方法,我们只需要使用Jackson2ObjectMapperBuilder进行配置就可以了。
大家有兴趣的话可以看下Jackson2ObjectMapperBuilder的源码即可
当然在JacksonAutoConfiguration有一个
@Bean
public StandardJackson2ObjectMapperBuilderCustomizer standardJacksonObjectMapperBuilderCustomizer(
ApplicationContext applicationContext,
JacksonProperties jacksonProperties) {
return new StandardJackson2ObjectMapperBuilderCustomizer(applicationContext,
jacksonProperties);
}
此类提供了通过yaml来配置Jackson的能力。通过查看
JacksonProperties类我们可以看到sb可以配置的选型
sb通过autoconfigure和ymal配置的方式提供了两种个性化的配置方式,大家可以根据自己的业务需求来选择,当然也可以深度的定制,完全的重写JacksonAutoConfiguration也是可以的。
网友评论