Spring MVC 中 @RestController 返回 XML 需添加 jackson-dataformat-xml 依赖,用 @JacksonXmlRootElement 和 @JacksonXmlProperty 标注实体类,并在控制器方法中指定 produces = MediaType.APPLICATION_XML_VALUE。
Spring MVC 中使用 @RestController 返回 XML 数据,核心在于让 Spring 能正确序列化对象为 XML,并设置响应的 Content-Type 为 appl。默认情况下,
ication/xml@RestController 依赖 Jackson(处理 JSON),要支持 XML 需额外配置和依赖。
在 Maven 的 pom.xml 中引入 jackson-dataformat-xml:
com.fasterxml.jackson.dataformat jackson-dataformat-xml
该依赖会自动注册 XmlMapper,Spring Boot 2.2+ 会自动识别并启用 XML 消息转换器(Jackson2ObjectMapperBuilder + MappingJackson2XmlHttpMessageConverter)。
用 Jackson 的注解标注 POJO,例如:
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
@JacksonXmlRootElement(localName = "user")
public class User {
@JacksonXmlProperty(localName = "id")
private Long id;
@JacksonXmlProperty(localName = "name")
private String name;
// getter/setter 省略
}
@JacksonXmlRootElement:指定根元素名@JacksonXmlProperty:控制字段对应 XML 元素名及是否作为属性(加 isAttribute = true)setVisibility 配置才能访问私有字段显式指定支持 XML 响应,推荐写法:
@GetMapping(value = "/user/{id}", produces = MediaType.APPLICATION_XML_VALUE)
public User getUser(@PathVariable Long id) {
return new User(id, "Alice");
}
produces = MediaType.APPLICATION_XML_VALUE 告诉 Spring 此接口只返回 XMLAccept: application/xml 时才会匹配(若同时支持 JSON 和 XML,可写 produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})produces 时,Spring 会根据请求头 Accept 自动协商,但需确保客户端明确指定如果返回仍是 JSON 或报 406 Not Acceptable 错误,检查以下几点:
jackson-dataformat-xml 及其 transitive 依赖如 woodstox-core)XmlHttpMessageConverter,看是否被注册curl -H "Accept: application/xml" http://localhost:8080/user/1
text/html,不会触发 XML,建议用 Postman 或 curl