'Set default response content type in Spring Boot REST API

Response content type on REST API endpoints (controller classes or methods) in Spring Boot can be set using the @Produces annotation. Is there a way to set this application wide as a default for every endpoint in the REST API? For example, instead of writing @Produces("application/json") on every controller class or endpoint, can this be set on the entry application class? Or is there any other way to configure a default used until explicitely overwritten?



Solution 1:[1]

If you want to set the default Accept header, not of default "Content-Type" header, so this solution will only impact responses, not requests.

As of Spring Boot 2.x, you need to create a class that extends the WebMvcConfigurer interface, e.g.:

@Configuration
class WebMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation( ContentNegotiationConfigurer configurer){
        configurer.defaultContentType( MediaType.APPLICATION_JSON );
    }
}

Let me know the result. Good luck.

Solution 2:[2]

Another option is to specify this default-media-type property in your application.properties:

spring.data.rest.default-media-type=application/json

Interestingly, it's also shown here as defaultMediaType. I believe you can use either the above or:

spring.data.rest.defaultMediaType=application/json

I'm not sure actually why there appear to be 2 ways to specify this same property.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Faramarz Afzali
Solution 2