在 Spring Boot 項目中使用 Swagger 文檔

Swagger 又稱絲襪哥,號稱可以讓程序員邊寫代碼邊生產接口文檔。

添加 Swagger 2 依賴

pom.xml 中添加 Swagger 2 所需依賴:

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>

添加 Swagger 的 Java 配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

  @Bean
  public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()
      .apis(RequestHandlerSelectors.any())
      .paths(PathSelectors.any())
      .build();
  }
}

Swagger 註解說明

Swagger 通過註解表明該接口會生成文檔,包括接口名、請求方法、參數、返回信息的等等。

  • @Api:修飾整個類,描述 Controller 的作用
  • @ApiOperation:描述一個類的一個方法,或者說一個接口
  • @ApiParam:單個參數描述
  • @ApiModel:用對象來接收參數
  • @ApiProperty:用對象接收參數時,描述對象的一個字段
  • @ApiResponse:HTTP 響應其中 1 個描述
  • @ApiResponses:HTTP 響應整體描述
  • @ApiIgnore:使用該註解忽略這個API
  • @ApiImplicitParam:一個請求參數
  • @ApiImplicitParams:多個請求參數

以上這些就是最常用的幾個註解了。

具體其他的註解,查看:https://github.com/swagger-api/swagger-core/wiki/Annotations

更多請參考 Swagger 註解文檔

添加 Controller、Model 來測試效果

@Api(value = "用戶管理", description = "用戶信息的「增、刪、查、改」操作")
@RestController
@RequestMapping(path = "/sample/users")
public class UserController {

  private static Map<Long, UserModel> users = Collections.synchronizedMap(new HashMap<>());

  @ApiOperation(value = "用戶列表")
  @GetMapping(path = "/")
  public List<UserModel> getUserList() {
    return new ArrayList<>(users.values());
  }

  @ApiOperation(value = "創建用戶", notes = "根據 User 對象創建用戶")
  @ApiImplicitParam(name = "user", value = "用戶詳細實體", required = true, dataTypeClass = UserModel.class)
  @PostMapping(path = "/")
  public UserModel createUser(@RequestBody UserModel user) {
    users.put(user.getId(), user);
    return user;
  }

  @ApiOperation(value = "用戶詳細信息", notes = "根據 ID 獲取用戶詳細信息")
  @ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataType = "Long")
  @GetMapping(path = "/{id}")
  public UserModel getUser(@PathVariable Long id) {
    return users.get(id);
  }

  @ApiOperation(value = "更新用戶詳細信息", notes = "根據 ID 指定更新對象, 並根據 User 信息來更新用戶詳細信息")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataTypeClass = Long.class),
      @ApiImplicitParam(name = "user", value = "用戶詳細實體", required = true, dataTypeClass = UserModel.class)
  })
  @PutMapping(path = "/{id}")
  public UserModel updateUser(@PathVariable Long id, @RequestBody UserModel user) {
    UserModel updateUser = users.get(id);
    updateUser.setName(user.getName());
    updateUser.setAge(user.getAge());
    updateUser.setEmail(user.getEmail());
    users.put(id, updateUser);
    return updateUser;
  }

  @ApiOperation(value = "刪除用戶", notes = "根據 ID 指定刪除對象")
  @ApiImplicitParam(name = "id", value = "用戶 ID", required = true, dataType = "Long")
  @DeleteMapping(path = "/{id}")
  public String deleteUser(@PathVariable Long id) {
    users.remove(id);
    return "success";
  }
}
@Data
@ApiModel(value = "用戶模型", description = "用戶詳細信息實體類")
public class UserModel {

  @ApiModelProperty(value = "用戶 ID")
  private Long id;

  @ApiModelProperty(value = "名字", allowableValues = "y0ngb1n, tony")
  private String name;

  @ApiModelProperty(value = "年齡", allowableValues = "range[1, 120]")
  private Integer age;

  @ApiModelProperty(value = "郵箱")
  private String email;
}

此時可以啓動項目進行驗證是否成功集成 Swagger 2 了,啓動項目後,在日誌中可以看到 Swagger 爲我們添加了訪問端點 /v2/api-docs

...
2019-12-28 22:19:53.880  INFO 11935 --- [main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
...

通過瀏覽器訪問 http://localhost:8080/v2/api-docs,可以發現返回的結果是一段 JSON 串,可讀性非常差。幸運的是 Swagger 2 爲我們提供了可視化的交互界面 SwaggerUI,下面我們就一起來試試吧。

添加 Swagger UI 依賴

同上面一樣,在 pom.xml 中添加 Swagger UI 所需依賴:

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
</dependency>

添加完成後,重新啓動項目,然後通過瀏覽器訪問 http://localhost:8080/swagger-ui.html,便以看到下面就效果:

到這裏就集成 Swagger 成功了,更多高階的操作就等繼續看文檔或下面的參考鏈接進一步摸索了,祝學習愉快!

🔗️ 參考鏈接


感謝您的閱讀,本文由 楊斌的博客 版權所有。
如若轉載,請註明出處:楊斌的博客(https://y0ngb1n.github.io?utm_source=jianshu

項目已託管於 GitHub:y0ngb1n/spring-boot-samples,歡迎 Star, Fork 😘


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章