You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot 2.7:配置全局控制器默认生产和消费JSON

配置Spring MVC默认生产和消费JSON的方法

当然可以通过全局配置实现,无需在每个控制器方法上重复添加注解,以下是几种可行方案:

1. Spring Boot 配置文件方式(推荐)

如果是Spring Boot项目,直接在配置文件中添加全局默认设置:

  • application.properties:
spring.mvc.default-content-type=application/json
spring.mvc.dispatch-options-request=true
  • application.yml:
spring:
  mvc:
    default-content-type: application/json
    dispatch-options-request: true

该配置会让框架默认将响应Content-Type设为JSON,同时默认接受JSON格式的请求体。

2. 自定义WebMvcConfigurer配置类

适用于传统Spring MVC项目或需要更灵活配置的场景,实现WebMvcConfigurer接口自定义内容协商规则:

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

@Configuration
public class GlobalWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        // 设置全局默认响应类型为JSON
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
        // 若需强制忽略请求头的Accept字段,始终返回JSON,可添加以下配置
        // configurer.ignoreAcceptHeader(true).favorPathExtension(false);
    }
}

3. 全局控制器基类

创建一个带全局@RequestMapping注解的基类,其他控制器继承该类即可共享配置:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public class BaseJsonController {
    // 业务控制器直接继承此类,无需重复配置注解
}

注意事项

  • 若个别方法需要特殊的produces/consumes(如返回XML),直接在方法上添加对应注解即可,方法级配置会覆盖全局设置。
  • 确保项目已引入Jackson相关依赖(Spring Boot的spring-boot-starter-web默认包含),否则无法完成JSON序列化/反序列化。

内容的提问来源于stack exchange,提问作者OTUser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:25:25