当我们获取 bean 时,SpringBoot WebMvcConfigurationSupport 没有采用 configureMessageConverters

SpringBoot WebMvcConfigurationSupport didn't take configureMessageConverters when we get bean in

WebMvcConfigurationSupport child class 中我们重写方法 configureMessageConverters.

当我们像豆子一样得到一个转换器时,

@Bean
public HttpMessageConverter mappingJackson2HttpMessageConverter(){
    MappingJackson2HttpMessageConverter jacksonConverter =
            new MappingJackson2HttpMessageConverter(new EventServiceObjectMapper());

    return jacksonConverter;
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new Jaxb2RootElementHttpMessageConverter());
    converters.add(mappingJackson2HttpMessageConverter());
}

configuration-loader 没有拿走我们的转换器。

但是当我们在方法中声明所有内容时,configuration-loader 带走了我们的转换器。

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new Jaxb2RootElementHttpMessageConverter());
    converters.add(new MappingJackson2HttpMessageConverter(new EventServiceObjectMapper()));
}

正常吗?我想念什么?

依赖关系::

Spring webmvc 4.3.22.RELEASE

SpringBoot 1.5.19.RELEASE

我找到了一种解决方案。扩展 WebMvcConfigurerAdapter,并实现 extendMessageConverters,清除转换器并仅设置我想要的转换器。

@Bean
public HttpMessageConverter mappingJackson2HttpMessageConverter(){
    MappingJackson2HttpMessageConverter jacksonConverter =
            new MappingJackson2HttpMessageConverter(new EventServiceObjectMapper());

    return jacksonConverter;
}

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.clear();
    converters.add(new Jaxb2RootElementHttpMessageConverter());
    converters.add(mappingJackson2HttpMessageConverter());
}

我一直在与 WebMVC 和 RestAPI 作斗争。一旦 @EnableWebMvc,它将覆盖 spring.jackson.* 配置。

我的解决方案,获取当前 MappingJackson2HttpMessageConverter 并根据需要自定义它。

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
    private ObjectMapper mapper;

    @Autowired  // spring.jackson.* ObjectMapper's config
    public WebConfig(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void extendMessageConverters (List<HttpMessageConverter<?>> converters) {
        converters.stream()
                .filter(x -> x instanceof  MappingJackson2HttpMessageConverter)
                .forEach(x -> ((MappingJackson2HttpMessageConverter) x).setObjectMapper(mapper));
    }
}