Abhijit Sarkar
Abhijit Sarkar

Reputation: 24538

What is the WebMvcConfigurationSupport replacement in Spring Boot?

In traditional Spring MVC, I can extend WebMvcConfigurationSupport and do the following:

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false).
    favorParameter(true).
    defaultContentType(MediaType.APPLICATION_JSON).
    mediaType("xml", MediaType.APPLICATION_XML);
}

How do I do this in a Spring Boot app? My understanding is that adding a WebMvcConfigurationSupport with @EnableWebMvc will disable the Spring Boot WebMvc autoconfigure, which I don't want.

Upvotes: 8

Views: 11643

Answers (2)

Björn Kahlert
Björn Kahlert

Reputation: 129

As of Spring 5.0 you can use the interface WebMvcConfigurer since Java 8 allows for default implementations on interfaces.

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

   ...
   @Override
   public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
      configurer.favorParameter(..);
      ...
      configurer.defaultContentType(..);
   }
}

Upvotes: 1

ikumen
ikumen

Reputation: 11643

Per Spring Boot reference on auto configuration and Spring MVC:

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc. If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Bean of type WebMvcConfigurerAdapter, but without @EnableWebMvc.

For example if you want to keep Spring Boot's auto configuration, and customize ContentNegotiationConfigurer:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

   ...
   @Override
   public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
      super.configureContentNegotiation(configurer);
      configurer.favorParameter(..);
      ...
      configurer.defaultContentType(..);
   }
}

Upvotes: 9

Related Questions