Spring Boot集成Swagger

Spring Boot集成Swagger

[TOC]html

前言

爲了完成項目自帶文檔的需求,花了必定的時間研究 Spring Boot集成 Swagger。看了官方文檔和一些博客,差很少搭出一個比較通用的架子。

文末會分享出案例項目。java

基本概述

本文使用 Spring Boot+ Spring Fox的方式集成 Swagger框架。

案例

引入依賴

<properties>
    <swagger.version>2.7.0</swagger.version>
</properties>
<dependencies>
    <!-- swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger.version}</version>
    </dependency>
    <!-- swagger2 ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger.version}</version>
    </dependency>
</dependencies>

Swagger配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.switchvov.swagger"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    /**
     * 配置認證模式
     */
    private List<ApiKey> securitySchemes() {
        return newArrayList(new ApiKey("Authorization", "Authorization", "header"));
    }

    /**
     * 配置認證上下文
     */
    private List<SecurityContext> securityContexts() {
        return newArrayList(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build());
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return newArrayList(new SecurityReference("Authorization", authorizationScopes));
    }

    /**
     * 項目信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger測試項目 RESTful APIs")
                .version("1.0")
                .build();
    }
}

配置方式

基本概述

Swagger官方Wiki 註解
swagger2經常使用註解說明
swagger註釋API詳細說明

PS:以上幾篇文章已經將Swagger註解的使用方式及做用闡述的很是清楚了。這裏只給出代碼案例。git

PS:springfox-swagger2:2.7.0已經支持泛型返回對象。
<font color='red'>注意:千萬不要在@ApiOperation註解裏限定response(),讓框架推斷類型就好了。</font>github

控制器

@RestController
@RequestMapping(value = "/user", produces = "application/json")
@Api(value = "User", tags = {"User"}, description = "用戶相關")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    @ApiOperation(value = "使用ID查詢用戶")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "ID", name = "id", dataType = "int", paramType = "path", required = true, defaultValue = "1")
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "請求參數有誤"),
            @ApiResponse(code = 401, message = "未受權"),
            @ApiResponse(code = 403, message = "禁止訪問"),
            @ApiResponse(code = 404, message = "請求路徑不存在"),
            @ApiResponse(code = 500, message = "服務器內部錯誤")
    })
    public ResponseResult<User> getById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return ResponseResult.successWithData(user);
    }

    @PostMapping("")
    @ApiOperation(value = "建立用戶")
    @ApiResponses({
            @ApiResponse(code = 400, message = "請求參數有誤"),
            @ApiResponse(code = 401, message = "未受權"),
            @ApiResponse(code = 403, message = "禁止訪問"),
            @ApiResponse(code = 404, message = "請求路徑不存在"),
            @ApiResponse(code = 500, message = "服務器內部錯誤")
    })
    public ResponseResult<User> createUser(@Validated @RequestBody User user) {
        User dbUser = userService.createUser(user);
        return ResponseResult.successWithData(dbUser);
    }
}

統一響應類

@ApiModel(description = "響應對象")
public class ResponseResult<T> {
    private static final int SUCCESS_CODE = 0;
    private static final String SUCCESS_MESSAGE = "成功";

    @ApiModelProperty(value = "響應碼", name = "code", required = true, example = "" + SUCCESS_CODE)
    private int code;

    @ApiModelProperty(value = "響應消息", name = "msg", required = true, example = SUCCESS_MESSAGE)
    private String msg;

    @ApiModelProperty(value = "響應數據", name = "data")
    private T data;

    // 省略get、set方法等等,詳見源代碼
}

用戶Model

PS:用戶model使用了 lombokjpavalidator,只須要關注 @Api開頭的註解就好了。
@Data
@Entity(name = "users")
@ApiModel(description = "用戶Model")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Null(message = "id必須爲空")
    @ApiModelProperty(value = "用戶ID", name = "id")
    private Integer id;

    @Column
    @NotBlank(message = "用戶名不能爲空")
    @ApiModelProperty(value = "用戶名", name = "username", required = true, example = "zhaoliu")
    private String username;

    @Column
    @NotBlank(message = "密碼不能爲空")
    @ApiModelProperty(value = "密碼", name = "password", required = true, example = "123456")
    private String password;
}

文檔界面

spring-swagger-1.png

spring-swagger-2.png

源碼

GitHub:swagger-demospring

參考信息

分享並記錄所學所見
相關文章
相關標籤/搜索