Spring 引导控制器建议 - 如何 return XML 而不是 JSON?

Spring Boot Controller Advice - How to return XML instead of JSON?

我有一个控制器建议 class,但我似乎无法将其提供给 return XML,即使我使用了 @RequestMapping 注释。这是一个精简的例子。

@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(Exception.class)
    @RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
    public PriceAvailabilityResponse handleControllerErrorXML(final Exception e){

        e.printStackTrace();
        System.out.println("Exception Handler functional");

        PriceAvailabilityResponse priceAvailabilityResponse = new PriceAvailabilityResponse();
        priceAvailabilityResponse.setStatusMessage("Server Error");
        priceAvailabilityResponse.setStatusCode(99);

        return priceAvailabilityResponse;
        }
}

请注意 @RequestMapping(produces = MediaType.APPLICATION_XML_VALUE) 如何在 rest 控制器中工作以控制响应的形成方式。

这里是 PriceAvailabilityResponse 可能来自上述代码块的示例。

    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @Getter
    @Setter
    public class PriceAvailabilityResponse {

        @JacksonXmlProperty(isAttribute = true, localName = "StatusCode")
        @JsonProperty(value = "StatusCode", required = false)
        private int statusCode = 0;

        @JacksonXmlProperty(isAttribute = true, localName = "StatusMessage")
        @JsonProperty(value = "StatusMessage", required = false)
        private String statusMessage;
    }

下面是抛出错误的示例 rest 控制器方法

@RequestMapping(value = "/error_test", produces = MediaType.APPLICATION_XML_VALUE)
public PriceAvailabilityResponse getPriceResponse() throws Exception{

    int x = 1/0;

    return null;
}

我已经将此代码的模型编写为 return JSON 和 XML,具体取决于哪个端点正在访问微服务,这是绝对必要的。

不幸的是,当我点击 /error_test 路径时,我的响应总是出现在 JSON 中。

如何强制响应为 XML?非常感谢您的宝贵时间。

以下方法应该可以解决您的问题

@RestController
public class TestController {

@GetMapping(value = "/throw-exception", produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity throwException(){
    throw new CustomException("My Exception");
}

}

Return 来自异常处理程序的响应实体并指定媒体类型。

@ControllerAdvice
public class GlobalErrorHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(value = {CustomException.class})
protected ResponseEntity handleInvalidDataException(
        RuntimeException ex, WebRequest request) {

    PriceAvailabilityResponse priceAvailabilityResponse = new 
    PriceAvailabilityResponse();
    priceAvailabilityResponse.setStatusMessage("Server Error");
    priceAvailabilityResponse.setStatusCode(99);

    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
            .contentType(MediaType.APPLICATION_XML)
            .body(priceAvailabilityResponse);
}

}

包括 jackson-dataformat-xml 依赖项(如果您没有)

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.9.8</version>
    </dependency>