1. 概述
本教程將簡要介紹 Swagger 的 <a href="https://docs.swagger.io/swagger-core/v1.5.0/apidocs/io/swagger/annotations/ApiParam.html"><em @ApiParam</em></a> 和<em @ApiModelProperty 註解。 此外,我們將比較這些註解並確定每種註解的正確用法。
2. 關鍵差異
簡單來説,@ApiParam 和 @ApiModelProperty 標註分別向 Swagger 添加不同的元數據。@ApiParam 標註用於 API 資源請求的參數,而@ApiModelProperty 則用於模型屬性。
3. @ApiParam
The @ApiParam annotation is for use solely with the JAX-RS 1.x/2.x parameter annotations like @PathParam, @QueryParam, @HeaderParam, @FormParam, and @BeanParam. Although swagger-core scans these annotations by default, we can use @ApiParam to add more details about the parameters or change the values as they are read from the code.
The @ApiParam annotation helps to specify the name, type, description (value), and example value of the parameter. Moreover, we can specify whether the parameter is required or optional.
Let’s look at its usage:
@RequestMapping(
method = RequestMethod.POST,
value = "/createUser",
produces = "application/json; charset=UTF-8")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
@ApiOperation(value = "Create user",
notes = "This method creates a new user")
public User createUser(
@ApiParam(
name = "firstName",
type = "String",
value = "First Name of the user",
example = "Vatsal",
required = true)
@RequestParam String firstName) {
User user = new User(firstName);
return user;
}讓我們來看一下 Swagger UI 對我們 @ApiParam 示例的表示:
現在,讓我們來看一下 @ApiModelProperty。
4. <em @ApiModelProperty
@ApiModelProperty 註解 允許我們控制 Swagger 相關的定義,例如描述(value)、名稱、數據類型、示例值和模型屬性的允許值。
此外,它還提供額外的過濾屬性,以便在某些場景下隱藏屬性。
讓我們為 User 的 firstName 字段添加幾個模型屬性:
@ApiModelProperty(
value = "first name of the user",
name = "firstName",
dataType = "String",
example = "Vatsal")
String firstName;現在,讓我們來查看 Swagger UI 中 User 模型規格:
5. 結論
在本文中,我們探討了兩種 Swagger 註解,用於為參數和模型屬性添加元數據。我們還查看了使用這些註解的示例代碼,並觀察了它們在 Swagger UI 中的表示形式。