SpringDoc V1 只支持到 Spring Boot 2.x
springdoc-openapi v1.7.0 is the latest Open Source release supporting Spring Boot 2.x and 1.x.
Spring Boot 3.x 要用 SpringDoc 2 / Swagger V3, 并且包名也改成了 springdoc-openapi-starter-webmvc-ui
SpringDoc V2 https://springdoc.org/v2/
配置
增加 Swagger 只需要在 pom.xml 中添加依賴
<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.3.0</version>
</dependency>
Spring Boot 啟動時就會自動啟用 Swagger, 從以下地址可以訪問 接口形式(JSON, YAML)和WEB形式的接口文檔
- http://host:port/context-path/v3/api-docs
- YAML格式 http://host:port/context-path/v3/api-docs.yaml
- http://host:port/context-path/swagger-ui/index.html
如果要關閉, 啟用, 自定義接口地址, 在 application.yml 中添加配置
springdoc:api-docs:path: /v3/api-docsenabled: false
對應WEB地址的配置為
springdoc:swagger-ui:path: /swagger-ui.htmlenabled: false
因為WEB界面的顯示基于解析JSON接口返回的結果, 如果api-docs關閉, swagger-ui即使enable也無法使用
在開發和測試環境啟動服務時, 可以用VM參數分別啟用
# in VM arguments
-Dspringdoc.api-docs.enabled=true -Dspringdoc.swagger-ui.enabled=true
使用注解
@Tag
Swagger3 中可以用 @Tag 作為標簽, 將接口方法進行分組. 一般定義在 Controller 上, 如果 Controller 沒用 @Tag 注解, Swagger3 會用Controller的類名作為默認的Tag, 下面例子用 @Tag 定義了一個“Tutorial”標簽, 帶有說明"Tutorial management APIs", 將該標簽應用于TutorialController后, 在 Swagger3 界面上看到的這個 Controller 下面的方法集合就是 Tutorial.
@Tag(name = "Tutorial", description = "Tutorial management APIs")
@RestController
@RequestMapping("/api")
public class TutorialController {//...
}
也可以將 @Tag 添加到單獨的方法上, 這樣在 Swagger3 界面上, 就會將這個方法跟同樣是 Tutorial 標簽的其它方法集合在一起.
public class AnotherController {@Tag(name = "Tutorial", description = "Tutorial APIs")@PostMapping("/tutorials")public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {//...}
}
@Operation
Swagger3中 @Operation注解用于單個API方法. 例如
public class MoreController {@Operation(summary = "Retrieve a Tutorial by Id",description = "Some description",tags = { "tutorials", "get" })@GetMapping("/tutorials/{id}")public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") long id) {//...}
}
用tags = { "tutorials", "get" }
可以將一個方法放到多個Tag分組中
@ApiResponses 和 @ApiResponse
Swagger3 使用 @ApiResponses 注解標識結果類型列表, 用@ApiResponse注解描述各個類型. 例如
public class AnotherController {@ApiResponses({@ApiResponse(responseCode = "200",content = { @Content(schema = @Schema(implementation = UserBO.class), mediaType = "application/json") }),@ApiResponse(responseCode = "404",description = "User not found.", content = { @Content(schema = @Schema()) })})@GetMapping("/user/{id}")public ResponseEntity<UserBO> getUserById(@PathVariable("id") long id) {return null;}
}
@Parameter
@Parameter注解用于描述方法參數, 例如:
@GetMapping("/tutorials")
public ResponseEntity<Map<String, Object>> getAllTutorials(@Parameter(description = "Search Tutorials by title") @RequestParam(required = false) String title,@Parameter(description = "Page number, starting from 0", required = true) @RequestParam(defaultValue = "0") int page,@Parameter(description = "Number of items per page", required = true) @RequestParam(defaultValue = "3") int size) {//...
}
@Schema annotation
Swagger3 用 @Schema 注解對象和字段, 以及接口中的參數類型, 例如
@Schema(description = "Tutorial Model Information")
public class Tutorial {@Schema(accessMode = Schema.AccessMode.READ_ONLY, description = "Tutorial Id", example = "123")private long id;@Schema(description = "Tutorial's title", example = "Swagger Tutorial")private String title;// getters and setters
}
accessMode = Schema.AccessMode.READ_ONLY
用于在接口定義中標識字段只讀
實例
定義接口
@Tag(name = "CRUD REST APIs for User Resource",description = "CRUD REST APIs - Create User, Update User, Get User, Get All Users, Delete User"
)
@Slf4j
@RestController
public class IndexController {@Operation(summary = "Get a user by its id")@GetMapping(value = "/user_get")public String doGetUser(@Parameter(name = "id", description = "id of user to be searched")@RequestParam(name = "id", required = true)String id) {return "doGetUser: " + id;}@Operation(summary = "Add a user")@PostMapping(value = "/user_add")public String doAddUser(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User to add.", required = true)@RequestBody UserBO user) {return "doAddUser: " + user.getName();}@ApiResponses({@ApiResponse(responseCode = "200",content = { @Content(schema = @Schema(implementation = UserBO.class), mediaType = "application/json") }),@ApiResponse(responseCode = "404",description = "User not found.", content = { @Content(schema = @Schema()) })})@GetMapping("/user/{id}")public ResponseEntity<UserBO> getUserById(@PathVariable("id") long id) {return null;}
}
對于這行代碼@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "User to add.", required = true)
,
因為 Swagger3 的 RequestBody 類和 Spring MVC 的 RequestBody 重名了, 所以在注釋中不得不用完整路徑, 比較影響代碼格式. 在GitHub上有對這個問題的討論(鏈接 https://github.com/swagger-api/swagger-core/issues/3628), 暫時無解.
定義對象
@Schema(description = "UserBO Model Information")
@Data
public class UserBO {@Schema(description = "User ID")private String id;@Schema(description = "User Name")private String name;
}
參考
- https://www.baeldung.com/spring-rest-openapi-documentation