Spring Boot接口如何根据请求格式返回对应JSON/XML响应
实现方案(Spring Boot 2.5.x 原生支持,无需硬编码)
1. 依赖检查
你当前pom.xml中已经引入了spring-boot-starter-web和jackson-dataformat-xml,Spring Boot会自动注册JSON、XML两类消息转换器,无需额外手动配置序列化逻辑。
2. 内容协商配置调整
你找到的旧教程配置是基于原生Spring MVC的,WebMvcConfigurerAdapter已经在Spring 5版本废弃,且Spring Boot项目不要加@EnableWebMvc注解(会覆盖Spring Boot默认的Web自动配置),直接使用如下配置即可:
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 ContentNegotiationConfig implements WebMvcConfigurer { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer // 关闭路径后缀匹配格式(如/test.xml这类格式识别) .favorPathExtension(false) // 关闭请求参数指定格式(如?format=xml这类格式识别) .favorParameter(false) // 开启Accept头识别 .ignoreAcceptHeader(false) // 未匹配到格式时的默认返回类型,可根据业务调整 .defaultContentType(MediaType.APPLICATION_XML) .mediaType("xml", MediaType.APPLICATION_XML) .mediaType("json", MediaType.APPLICATION_JSON); } }
如果需要严格实现请求是什么格式就返回什么格式(和请求的Content-Type强制绑定,忽略Accept头),只需要新增一个自定义内容协商策略,调整配置即可:
// 自定义协商策略 import org.springframework.web.accept.ContentNegotiationStrategy; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.http.MediaType; import java.util.Collections; import java.util.List; public class RequestContentTypeBindStrategy implements ContentNegotiationStrategy { @Override public List<MediaType> resolveMediaTypes(NativeWebRequest request) { String contentType = request.getHeader("Content-Type"); if (contentType != null) { try { MediaType reqMediaType = MediaType.parseMediaType(contentType); // 只匹配支持的JSON、XML格式 if (reqMediaType.isCompatibleWith(MediaType.APPLICATION_JSON) || reqMediaType.isCompatibleWith(MediaType.APPLICATION_XML)) { return Collections.singletonList(reqMediaType); } } catch (Exception ignored) {} } // 匹配失败返回默认格式 return Collections.singletonList(MediaType.APPLICATION_XML); } }
调整配置类的配置项:
@Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer .defaultContentTypeStrategy(new RequestContentTypeBindStrategy()) .mediaType("xml", MediaType.APPLICATION_XML) .mediaType("json", MediaType.APPLICATION_JSON); }
3. 补充响应类注解
你的TransactionRequest已经添加了@XmlRootElement和@JsonRootName注解,给对应的TransactionResponse类也加上同样的注解即可,保证序列化后的根节点名称符合格式要求。
4. 验证规则
你接口上配置的produces = {"application/xml", "application/json"}符合规范要求,Spring会自动校验:
- 请求头
Content-Type: application/xml时返回XML格式响应 - 请求头
Content-Type: application/json时返回JSON格式响应 - 不支持的请求格式会直接返回415错误,不符合的返回格式要求会返回406错误
内容的提问来源于stack exchange,提问作者NPE_founder
相关产品推荐
相关产品推荐

