在Linux系統中,Swagger(現在通常指的是OpenAPI)是一種用于設計、構建、記錄和使用RESTful Web服務的框架。Swagger注解是用于描述API接口和模型的元數據,它們可以幫助開發者更好地理解API的功能和使用方法。
以下是一些常見的Swagger注解及其用法:
@ApiOperation
:用于描述一個API接口的作用。
@ApiOperation(value = "獲取用戶信息", notes = "根據用戶ID獲取用戶詳細信息")
@ApiParam
:用于描述API接口的參數。
@ApiParam(name = "userId", value = "用戶ID", required = true, example = "123")
@ApiResponses
和 @ApiResponse
:用于描述API接口可能的響應。
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功"),
@ApiResponse(code = 400, message = "請求參數錯誤"),
@ApiResponse(code = 404, message = "用戶不存在")
})
@ApiModel
和 @ApiModelProperty
:用于描述模型類及其屬性。
@ApiModel(description = "用戶信息")
public class User {
@ApiModelProperty(value = "用戶ID", example = "123")
private String userId;
@ApiModelProperty(value = "用戶名", example = "John Doe")
private String username;
// getters and setters
}
@ApiImplicitParam
和 @ApiImplicitParams
:用于描述非模型參數,如請求頭、路徑參數等。
@ApiImplicitParams({
@ApiImplicitParam(name = "Authorization", value = "訪問令牌", required = true, dataType = "string", paramType = "header")
})
@ApiIgnore
:用于忽略某個模型或模型屬性,使其不被Swagger文檔生成。
@ApiIgnore
public class SomeClass {
// ...
}
@Tag
:用于對API進行分組,可以在OpenAPI 3.0中使用。
@Tag(name = "用戶管理", description = "用戶相關的API")
@Parameter
:用于描述參數的詳細信息,可以在OpenAPI 3.0中使用。
@Operation(summary = "獲取用戶信息")
@Parameter(name = "userId", in = ParameterIn.PATH, required = true, description = "用戶ID", example = "123")
這些注解通常與Springfox或SpringDoc等庫一起使用,以自動生成Swagger文檔。在使用這些注解時,應確保你的項目中已經包含了相應的依賴,并且配置了Swagger相關的Java配置類。這樣,當你啟動應用程序時,Swagger UI將會自動可用,你可以通過瀏覽器訪問它來查看和測試你的API。