Spring Boot 集成 swagger2

在開(kāi)發(fā)過(guò)程中,為了實(shí)現(xiàn)前后端高效的溝通,通常需要提供相關(guān)的接口文檔。

Swagger2可以輕松的整合到SpringBoot中,并與SpringMVC程序配合組織出強(qiáng)大RESTful API文檔。它既可以減少我們創(chuàng)建文檔的工作量,也可以讓我們?cè)谛薷拇a邏輯的同時(shí)修改文檔說(shuō)明。此外Swagger2也提供了強(qiáng)大的頁(yè)面測(cè)試功能來(lái)調(diào)試每個(gè)RESTful API。

本文主要介紹Spring Boot 2.0 與 Swagger2的整合。

一、swagger 注解

@Api:用在請(qǐng)求的類上,表示對(duì)類的說(shuō)明
    tags="說(shuō)明該類的作用,可以在UI界面上看到的注解"
    value="該參數(shù)沒(méi)什么意義,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在請(qǐng)求的方法上,說(shuō)明方法的用途、作用
    value="說(shuō)明方法的用途、作用"
    notes="方法的備注說(shuō)明"

@ApiImplicitParams:用在請(qǐng)求的方法上,表示一組參數(shù)說(shuō)明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個(gè)請(qǐng)求參數(shù)的各個(gè)方面
        name:參數(shù)名
        value:參數(shù)的漢字說(shuō)明、解釋
        required:參數(shù)是否必須傳
        paramType:參數(shù)放在哪個(gè)地方
            · header --> 請(qǐng)求參數(shù)的獲取:@RequestHeader
            · query --> 請(qǐng)求參數(shù)的獲?。篅RequestParam
            · path(用于restful接口)--> 請(qǐng)求參數(shù)的獲取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:參數(shù)類型,默認(rèn)String,其它值dataType="Integer"       
        defaultValue:參數(shù)的默認(rèn)值

@ApiResponses:用在請(qǐng)求的方法上,表示一組響應(yīng)
    @ApiResponse:用在@ApiResponses中,一般用于表達(dá)一個(gè)錯(cuò)誤的響應(yīng)信息
        code:數(shù)字,例如400
        message:信息,例如"請(qǐng)求參數(shù)沒(méi)填好"
        response:拋出異常的類

@ApiModel:用于類上,表示一組數(shù)據(jù)的信息
            (這種一般用在post創(chuàng)建的時(shí)候,使用@RequestBody這樣的場(chǎng)景,
            請(qǐng)求參數(shù)無(wú)法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)
    @ApiModelProperty:用在屬性上,描述屬性

二、添加依賴

        <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>

三、配置Swagger

package pers.simon.boot.validator.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * swagger2 配置
 *
 * @author simon
 * @date 2019/12/12 13:57
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 實(shí)例化一個(gè) Docket Bean
     * <p></p>
     * <b>
     * 這個(gè)Bean中,配置映射路徑和要掃描的接口的位置,在apiInfo中,主要配置一下Swagger2文檔網(wǎng)站的信息,例如網(wǎng)站的title,網(wǎng)站的描述,聯(lián)系人的信息,使用的協(xié)議等等
     * </b>
     *
     * @return Docket Bean
     */
    @Bean
    public Docket createDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")//默認(rèn)請(qǐng)求都是以 / 根路徑開(kāi)始,如果我們的應(yīng)用不是部署在根路徑,比如以/validator部署,則可以通過(guò)一下方式設(shè)置請(qǐng)求的統(tǒng)一前綴
                .select()
                .apis(RequestHandlerSelectors.basePackage("pers.simon.boot.validator.controller"))//
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder()
                        .title("Spring Boot 參數(shù)校驗(yàn)")
                        .description("使用 validator 對(duì)入?yún)⑦M(jìn)行校驗(yàn)。包含自定義規(guī)則校驗(yàn),分組校驗(yàn),全局異常處理等")
                        .version("1.0.0")
                        .contact(new Contact("simon", "www.baidu.com", "simon@126.com"))
                        .license("The Apache License")
                        .licenseUrl("www.baidu.com")
                        .build()
                );

    }
}

四、接口

package pers.simon.boot.validator.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import pers.simon.boot.validator.annotate.Create;
import pers.simon.boot.validator.annotate.Update;
import pers.simon.boot.validator.po.UserVo;
import pers.simon.boot.validator.utils.JsonResult;

import javax.validation.constraints.NotEmpty;

/**
 *
 * @author simon
 * @date 2019/12/10 10:39
 */
@Api(tags = "用戶管理")
@RestController
@Validated
public class UserController {

    @ApiOperation("添加用戶")
    @PostMapping("/user")
    @ApiImplicitParam(name = "userVo", value = "用戶信息表單", required = true, dataType = "UserVo")
    public JsonResult saveUser(@RequestBody @Validated(Create.class) UserVo userVo){
        return JsonResult.success(userVo);
    }

    @ApiOperation("修改用戶")
    @ApiImplicitParam(name = "userVo", value = "用戶信息表單", required = true, dataType = "UserVo")
    @PutMapping("/user")
    public JsonResult updateUser(@RequestBody @Validated(Update.class) UserVo userVo){
        return JsonResult.success(userVo);
    }

    @ApiOperation("注銷用戶")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用戶ID",defaultValue = "",required = true),
            @ApiImplicitParam(name = "deptId",value = "部門ID",defaultValue = "",required = true)
    })
    @PatchMapping("/user")
    public JsonResult disableUser(@NotEmpty(message = "用戶ID不能為空")String userId, @NotEmpty(message = "所屬部門ID不能為空")String deptId){
        return JsonResult.success(userId);
    }
}

入?yún)serVo

package pers.simon.boot.validator.po;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import pers.simon.boot.validator.annotate.Create;
import pers.simon.boot.validator.annotate.IdCard;
import pers.simon.boot.validator.annotate.Update;

import javax.validation.constraints.*;
import java.util.Date;

/**
 * @author simon
 * @date 2019/12/10 10:28
 */
@ApiModel(description = "用戶信息表單")
@Data
public class UserVo {

    @ApiModelProperty(value = "用戶ID", name = "userId", required = true, example = "123")
    @Null(message = "用戶ID必須為空",groups = Create.class)
    @NotBlank(message = "用戶ID不能為空",groups = Update.class)
    private String userId;

    @ApiModelProperty(value = "用戶名稱", name = "userName", required = true, example = "admin")
    @NotBlank(message = "用戶名不能為空")
    private String userName;

    @ApiModelProperty(value = "生日", name = "birthday", required = true, example = "2019-11-02")
    @Past(message = "生日必須為過(guò)去日期")
    @NotNull(message = "生日不能為空")
    private Date birthday;

    @ApiModelProperty(value = "年齡", name = "age", required = true, example = "11", dataType = "int")
    @Min(value = 10,message = "年齡必須大于10")
    @Max(value = 30,message = "年齡必須小于30")
    @NotNull(message = "年齡不能為空")
    private Integer age;

    @ApiModelProperty(value = "郵箱", name = "email", required = true, example = "11@qq.com")
    @NotBlank(message = "郵箱不能為空")
    @Email(message = "郵箱格式錯(cuò)誤")
    private String email;

    @ApiModelProperty(value = "手機(jī)號(hào)", name = "phone", required = true, example = "12345678900")
    @NotNull(message = "手機(jī)號(hào)不能為空")
    @NotBlank(message = "手機(jī)號(hào)不能為空")
    @Pattern(regexp ="^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手機(jī)號(hào)格式有誤")
    @Max(value = 11,message = "手機(jī)號(hào)只能為11位")
    @Min(value = 11,message = "手機(jī)號(hào)只能為11位")
    private String phone;

    @ApiModelProperty(value = "身份證號(hào)", name = "idCard", required = true, example = "12345678900")
    @NotBlank(message = "身份證不能為空")
    @IdCard(message = "身份證不合法")
    private String idCard;
}

六、測(cè)試

訪問(wèn):http://localhost:8080/swagger-ui.html

2aa6d12ee2d2ad060698cce87e45a6c.png

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容