且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring boot - 如果请求中不存在,则设置默认的 Content-type 标头

更新时间:2021-07-07 08:18:45

从 Spring Boot 2.x 开始,您需要创建一个扩展 WebMvcConfigurer 接口的类,例如:

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 );
    }
}

在 1.x 下,您可以使用 WebMvcConfigurerAdapter 做同样的事情,现在已弃用.

Under 1.x, you could do the same thing with WebMvcConfigurerAdapter, which is now deprecated.

这将影响请求和响应主体,因此如果您没有明确设置生产"参数,并且您想要除 application/json 之外的其他内容,它将被强制转换为 application/json.

This will affect both request and response bodies, so if you do not have a "produces" parameter explicitly set, and you wanted something other than application/json, it's going to get coerced to application/json.