SpringBoot整合Swagger2,形成接口文檔

當然,首先是創建一個Spring Boot項目,加入web依賴,創建成功後,加入兩個Swagger2相關的依賴,完整的依賴如下:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Swagger2配置

Swagger2的配置也是比較容易的,在項目創建成功之後,只需要開發者自己提供一個Docket的Bean即可,如下:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 通過 createRestApi函數來構建一個DocketBean
     * 函數名,可以隨意命名,喜歡什麼命名就什麼命名
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//調用apiInfo方法,創建一個ApiInfo實例,裏面是展示在文檔頁面信息內容
                .select()
                
                .apis(RequestHandlerSelectors.basePackage("cn.com.zz.flow.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //構建 api文檔的詳細信息函數
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //頁面標題
                .title("SpringBoot整合Swagger2 構建RESTful API")
                //條款地址
                .termsOfServiceUrl("http://despairyoke.github.io/")
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }

如此,Swagger2就算配置成功了,非常方便。

此時啓動項目,輸入http://localhost:8080/swagger-ui.html,能夠看到如下頁面,說明已經配置成功了:

創建接口

接下來就是創建接口了,Swagger2相關的註解其實並不多,而且很容易懂,下面我來分別向小夥伴們舉例說明:

@RestController
@RequestMapping("/flow/user")
@Api(tags= "個人收藏夾接口")
public class BoxUserCollectController {

    @Autowired
    private BoxUserCollectService boxUserCollectService;

    @ApiOperation(value = "獲取用戶信息", notes = "獲取用戶信息")
    @RequestMapping(value = "/getUserAndMail", method = RequestMethod.POST)
    public APIResponse getUserAndMail(@RequestParam(name = "name", required = true) String name){
        if(name == null || "".equals(name)){
            return  APIResponse.fail("姓名必填");
        }
        List<BoxUserCollectEntity> list = boxUserCollectService.getUserMail(name);
        if(list != null && list.size() > 0){
            return  APIResponse.success(list);
        }
        return  APIResponse.success("沒有查詢到該用戶信息");
    }
    @ApiOperation(value = "添加個人收藏用戶", notes = "添加個人收藏用戶")
    @RequestMapping(value = "/addUserList", method = RequestMethod.POST)
    public APIResponse addUserList(@RequestParam(name = "userCode", required = true) String userCode,
                                   @RequestBody @ApiParam(name="list",value="傳入json格式",required=true) List<BoxUserCollectEntity> list){
        try {
            boxUserCollectService.add(list,userCode);
            return  APIResponse.success();
        }catch (Exception e){
            e.printStackTrace();
            return  APIResponse.fail("添加失敗");
        }
    }
    @ApiOperation(value = "查詢用戶收藏", notes = "收藏用戶名")
    @RequestMapping(value = "/getUserByCode", method = RequestMethod.POST)
    public APIResponse getUserByCode(@RequestParam(name = "userCode", required = true) String userCode){
        List<BoxUserCollectEntity> list = boxUserCollectService.getUserList(userCode);
        return APIResponse.success(list);
    }

這裏邊涉及到多個API,我來向小夥伴們分別說明:

@Api註解可以用來標記當前Controller的功能。
@ApiOperation註解用來標記一個方法的作用。
@ApiImplicitParam註解用來描述一個參數,可以配置參數的中文含義,也可以給參數設置默認值,這樣在接口測試的時候可以避免手動輸入。
如果有多個參數,則需要使用多個@ApiImplicitParam註解來描述,多個@ApiImplicitParam註解需要放在一個@ApiImplicitParams註解中。
需要注意的是,@ApiImplicitParam註解中雖然可以指定參數是必填的,但是卻不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架內必填,拋棄了Swagger2,這個限制就沒用了,所以假如開發者需要指定一個參數必填,@RequestParam(required = true)註解還是不能省略。
如果參數是一個對象(例如上文的更新接口),對於參數的描述也可以放在實體類中。例如下面一段代碼:

@Data
@ApiModel("收藏用戶類")
public class BoxUserCollectEntity extends Page implements Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * id
     */
    @ApiModelProperty(value = "用戶id")
    private String id;
    /**
     * 收藏用戶名稱
     */
    @ApiModelProperty(value = "收藏用戶名")
    private String userCode;
    /**
     * 被收藏用戶名稱
     */
    @ApiModelProperty(value = "被收藏用戶名", required = true)
    private String nameDisplay;
    /**
     * 被收藏地址
     */
    @ApiModelProperty(value = "被收藏郵箱地址", required = true)
    private String email;
    /**
     * 創建時間
     */
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(value = "創建時間")
    private Date createTime;

    /**
     * 狀態 1 已存在 0 表示 刪除
     */
    @ApiModelProperty(value = "狀態")
    private String status;

}

測試接口:

返回接口:

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