我想在我的方法中添加一个与斯瓦格的例子,我已经尝试了一些事情,但他们没有工作。
我有自己的接口,在其中定义方法:
@Api(value = "test API")
@RequestMapping("/api/v1/product")
public interface TestController {
@ApiOperation(
value = "Service that return a Product",
notes = "This service returns a Product by the ID",
nickname = "getProductById",
response = ProductResponse.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The request has succeeded.", response = ProductResponse.class),
@ApiResponse(code = 500, message = "Internal server error.", response = ProductResponse.class) })
@GetMapping(
value = "/productById",
produces = { "application/json" }
)
ResponseEntity<ProductResponse> getProductById(@RequestParam(value = "productId", required = true) String productId);
ProductResponse类如下所示:
@Getter
@Setter
@AllArgsConstructor
public class ProductResponse {
private Product product;
private CustomException customException;
}
Product类如下所示:
@Getter
@Setter
@AllArgsConstructor
public class Product {
@JsonProperty("id")
private String id;
@JsonProperty("productName")
private String productName;
@JsonProperty("productDescription")
private String productDescription;
@JsonProperty("unitPrice")
private Double unitPrice;
CustomException类如下所示:
@Getter
public class CustomException {
private final String message;
private final String errorCode;
private final String errorType;
private final Exception exceptionDetail;
public CustomException(String message, String errorCode, String errorType, Exception exceptionDetail) {
this.message = message;
this.errorCode = errorCode;
this.errorType = errorType;
this.exceptionDetail = exceptionDetail;
}
当响应为200时,响应如下所示:
{
"product": {
"id": "12345",
"productName": "Product name",
"productDescription": "This is a description",
"unitPrice": 3.25
},
"customException": null
}
但当响应为500时,响应如下所示:
{
"product": "null,",
"customException": {
"message": "/ by zero",
"errorCode": "500",
"errorType": "Internal server error",
"exceptionDetail": null,
"cause": null,
"stackTrace": [
{
"classLoaderName": "app",
"moduleName": null,
"moduleVersion": null,
"methodName": "getProductById",
"fileName": "TestControllerImpl.java",
"lineNumber": 33,
"className": "com.myproject.testmicroservice.controller.impl.TestControllerImpl",
"nativeMethod": false
}
]
}
}
如何在@ApiResponse注解中添加自定义示例?
3条答案
按热度按时间5n0oy7gb1#
您可能遗漏了
@Operation
注解,而您在其中放置了@ApiResponse
。示例:
kqqjbcuj2#
您可以尝试类似this的方法。在您的控制器中,您已经有了
@ApiResponses
注解。您需要做的是将@ApiModel
添加到您的Product
类中,然后将Product
类的成员,即ProductResponse
和CustomException
。需要验证的一件事是,是否可以在ProductResponse
和CustomException
等自定义对象上设置@ApiModelProperty
。如果不能,则需要将@ApiModelProperty
设置为1级深。如文章中所示,这些示例是从模型属性自动填充到响应的。
PS:到目前为止,我还没有一个昂首阔步的项目设置,所以只能在理论上帮助你。
jtw3ybtb3#
晚上好,希望你一切都好。在你所描述的情况下,我会这样做
所描述的方法在here中进行了解释。我认为第9段。使用@Operation和@ApiResponses生成文档对您的情况特别有用。希望这对您有所帮助,祝您晚安