如何扩展spring boot自动配置的行为?

时间:2015-07-15 01:57:11

标签: spring-boot

我希望在创建构建器时专门扩展JacksonAutoConfiguration,我想将ObjectMapper设置为具有ObjectMapper静态setter的Util类。在返回构建器之前查看该行,我想将ObjectMpper设置为静态类。

@Bean
        @ConditionalOnMissingBean(Jackson2ObjectMapperBuilder.class)
        public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder() {
            Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
            builder.applicationContext(this.applicationContext);
            if (this.jacksonProperties.getSerializationInclusion() != null) {
                builder.serializationInclusion(this.jacksonProperties
                        .getSerializationInclusion());
            }
            configureFeatures(builder, this.jacksonProperties.getDeserialization());
            configureFeatures(builder, this.jacksonProperties.getSerialization());
            configureFeatures(builder, this.jacksonProperties.getMapper());
            configureFeatures(builder, this.jacksonProperties.getParser());
            configureFeatures(builder, this.jacksonProperties.getGenerator());
            configureDateFormat(builder);
            configurePropertyNamingStrategy(builder);
            configureModules(builder);
            **ObjectMapperUtils.setObjectMapper( builder.build() );**
            return builder;
        }

1 个答案:

答案 0 :(得分:2)

从自动配置的ObjectMapper创建的Jackson2ObjectMapperBuilderJacksonAutoConfiguration中公开为bean。您可以简单地创建另一个@Configuration类,获取对ObjectMapper的引用(通过自动布线)并使用@PostConstruct方法在{{1}中设置ObjectMapper }。class。

另一个建议是重构ObjectMapperUtils以便将其创建为Spring bean本身,然后您可以直接将ObjectMapperUtils自动连接到其中。