springboot2.x基礎教程:Swagger詳解給你的介面加上文檔說明

相信無論是前端還是後端開發,都或多或少地被介面文檔折磨過。前端經常抱怨後端給的介面文檔與實際情況不一致。後端又覺得編寫及維護介面文檔會耗費不少精力,經常來不及更新。其實無論是前端調用後端,還是後端調用後端,都期望有一個好的介面文檔。
SpringBoot集成Swagger能夠通過很簡單的註解把介面描述清楚,生成可視化文檔頁面。
原生的Swagger-ui介面很粗糙,這裡用knife4j-spring-ui替代。

一個好的HTTP介面文檔描述

  1. 寫清楚介面的請求路徑: QueryPath: /user/login
  2. 寫清楚介面的請求方法類型: GET/POST/DELETE/PUT
  3. 寫清楚介面的業務含義,使用場景
  4. 寫清楚介面的入參:參數描述、參數類型、參數結構、參數是否必傳
  5. 寫清楚介面的返回類型:返回的數據結構,異常狀況

SpringBoot集成Swagger

項目引入依賴

        <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>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-ui</artifactId>
            <version>2.0.4</version>
        </dependency>

SpringBoot關於Swagger配置

把此Swagger配置粘入項目即可

@EnableSwagger2
@Configuration
public class SwaggerConfig implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
				//這裡改成自己的介麵包名
                .apis(RequestHandlerSelectors.basePackage("vip.codehome.springboot.tutorials.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot教程介面文檔")//標題
                .description("使用swagger文檔管理介面")//描述
                .contact(new Contact("codehome", "", "[email protected]"))//作者資訊
                .version("1.0.0")//版本號
                .build();
    }
	//解決doc.html,swagger-ui.html 404問題
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");

    }
}

Swagger的具體使用

各個註解的作用

  1. @Api 放在類上介紹類的作用
  2. @ApiOperation 放在方法上介紹方法的作用
  3. @ApiImplicitParam介紹入參說明
  4. @ApiResponse介紹返回狀態
  5. @ApiModel、@ApiModelProperty介紹入參是對象,返回是對象欄位說明

程式碼示例

@RestController
@Api(tags = "Swagger註解測試類")
public class SwaggerUserController {
    @ApiOperation(value = "這是一個echo介面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "msg",value = "請求的msg參數",required = true,paramType = "query"),
            @ApiImplicitParam(name = "token",value = "請求的token",required = false,paramType ="header" )
    })
    @ApiResponses({
            @ApiResponse(code=200,message = "請求成功"),
            @ApiResponse(code=400,message="請求無許可權")
    })
    @GetMapping("/echo")
    public String echo(String msg,@RequestHeader(name = "token") String token){
        return msg;
    }
    @PostMapping("/login")
    public R<UserInfoVO> login(@RequestBody LoginDTO loginDTO){
        UserInfoVO userInfoVO=new UserInfoVO();
        userInfoVO.setNickname("編程之家");
        userInfoVO.setToken("xxx");
        return R.ok(userInfoVO);
    }
}
@Data
@ApiModel
public class LoginDTO {
    @ApiModelProperty(value = "用戶帳號或者郵箱")
    String account;
    @ApiModelProperty(value = "用戶密碼")
    String passwd;
    @ApiModelProperty(value = "用戶密碼")
    String verifyCode;
}

介面文檔效果

這裡訪問的是//localhost:8080/doc.html,knife4j-spring-ui還有相比原生還有更多強大的功能,大家自行發現。
千里之行,始於足下。這裡是SpringBoot教程系列第二篇,所有項目源碼均可以在我的GitHub上面下載源碼。