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.
Class WebMvcConfigurationSupport. This is the main class providing the configuration behind the MVC Java config. It is typically imported by adding @EnableWebMvc to an application @Configuration class.
Configure a handler to delegate unhandled requests by forwarding to the Servlet container's "default" servlet. A common use case for this is when the DispatcherServlet is mapped to "/" thus overriding the Servlet container's default handling of static resources. This implementation is empty.
DispatcherServlet is the front controller in Spring Web MVC. Incoming requests for the HTML file are forwarded to the DispatcherServlet.
The @EnableWebMvc annotation is used for enabling Spring MVC in an application and works by importing the Spring MVC Configuration from WebMvcConfigurationSupport.
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(..);
}
}
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(..);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With