如何在springboot中,全局配置produces="text/plain;charset=UTF-8"

alwaysmove / 2024-10-11 / 原文

为什么要使用produces="text/plain;charset=UTF-8"?

当不用这个配置时,接口返回的数据,是有斜杠的

 配置后,就正常了

 

以前我的配置方式,是在每个接口上,都添加上produces="text/plain;charset=UTF-8"。但是这样显示不太好,每个接口都加的话,会比较耗费时间

如何做到全局配置

使用 WebMvcConfigurer

可以实现 WebMvcConfigurer 接口并重写 configureContentNegotiation 方法,以设置默认的 produces 类型。以下是示例代码:

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

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