dschulten
dschulten

Reputation: 3122

Adding custom HttpMessageConverter to spring-boot/spring-data-rest application

I want to add a custom HttpMessageConverter to a spring-boot application with spring data rest, but it turns out there are several places I have to inject my message converter. As a reference project for this situation, take https://github.com/olivergierke/spring-restbucks.

I am able to add my message converter by putting this into the basic configuration class, Restbucks.java:

@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {

    return new RepositoryRestConfigurerAdapter() {

        @Override
        public void configureHttpMessageConverters(
              List<HttpMessageConverter<?>> messageConverters) {
            messageConverters.add(0, myMessageConverter());
        }

    };
}

@Bean
public WebMvcConfigurer webMvcConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void configureMessageConverters(
                List<HttpMessageConverter<?>> messageConverters) {
            messageConverters.add(0, myMessageConverter());
        }
    };
}

Adding both is necessary because there are two different sets of message converters, available in the following beans:

A bean named restmappingHandlerAdapter from WebMvcAutoConfiguration$EnableWebMvcConfiguration - has 14 message converters including mine, handles /pages and /engine

A bean named repositoryExporterHandlerAdapter from SpringBootRepositoryRestMvcConfiguration - has 6 message converters, including my message converter, and handles /orders

As a workaround, I add my message converter twice, as shown above.

But why are there two distinct sets of message converters to customize? Why do /pages and /engine use a different setup than /orders? Is there some misconfiguration going on or is that how it is supposed to be?

Upvotes: 2

Views: 1336

Answers (1)

adam p
adam p

Reputation: 1214

I believe this is how it is supposed to be. I'd presume that the configuration of Spring Web MVC is separate to the config of Spring Data Rest so that they will play nice together, and so that you can customise the SDR repository exporter output without messing with your vanilla MVC controller output, and vice versa.

So any endpoint that is managed by SDR uses the SDR set, any other custom controller will use the Web MVC set.

Upvotes: 2

Related Questions