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

时间:2019-02-11 08:35:43

标签: java spring-boot spring-mvc converters

WebMvcConfigurationSupport子类中,我们重写了方法configureMessageConverters

当我们得到一个像bean这样的转换器时,

@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。发布

2 个答案:

答案 0 :(得分:0)

我找到了一个解决方案。扩展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());
}

答案 1 :(得分:0)

我在与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));
    }
}