Since updating to the latest version of Spring-Boot (1.4.1) I've noticed that in my RestControllers even though I'm explicitly setting the media type produced to "application/json" it is now producing "application/json;charset=UTF-8"
Controller:
@RestController
@RequestMapping(value = "/api/1/accounts", consumes = "application/json", produces = "application/json")
public class AccountController {
.....
Response Header
Content-Type →application/json;charset=UTF-8
Is there now somewhere else where this is configured which is overriding the RequestMapping setting?
@RestController annotation is a special controller used in RESTful Web services, and it's the combination of @Controller and @ResponseBody annotation. It is a specialized version of @Component annotation. It is a specialized version of @Controller annotation. In @Controller, we can return a view in Spring Web MVC.
Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.
@RestController annotation declares a Spring @Component whose scope is by default SINGLETON . This is documented in the @Scope annotation: Defaults to an empty string ("") which implies SCOPE_SINGLETON. This means that it will be the same instance of TestController that will handle every requests.
@RestController is not meant to be used to return views to be resolved. It is supposed to return data which will be written to the body of the response, hence the inclusion of @ResponseBody .
As per OrangeDog's comment above the MappingJackson2HttpMessageConverter handles the charset. This has been updated recently to add the default charSet if none is specified in message (i.e. via the RequestMapping produces config)
This can be overridden by implementing the below bean and setting the charSet to null:
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jsonConverter.setObjectMapper(objectMapper);
jsonConverter.setDefaultCharset(null);
return jsonConverter;
}
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