天天看點

Spring Boot 整合 Swagger2

文章目錄

    • 1 建立工程
      • 1.1 手動內建(老版本,無 Starter)
      • 1.2 自動內建(新版本,使用 Starter)
    • 2 Swagger2 配置
    • 3 使用
    • 4 Spring Security 中的配置

學習在 Spring Boot 中使用 Swagger2 實時生成線上接口文檔,還支援接口測試。特别是在前後端分離開發時,可以說是一大神器。

1 建立工程

1.1 手動內建(老版本,無 Starter)

建立 Spring Boot 項目

spring-boot-swagger2

,添加

Web

依賴。之後手動在 pom 檔案中添加 Swagger2 相關的兩個依賴,最終的依賴如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

    <!-- 1.5.21版本覆寫預設的1.5.20版本,解決@ApiModelProperty的example預設值類型轉換異常BUG - java.lang.NumberFormatException: For input string: "" -->
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.21</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-models</artifactId>
        <version>1.5.21</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>
           

1.2 自動內建(新版本,使用 Starter)

注:springfox 3.0.0 版本開始已經有對應的官方 Spring Boot Starter,在 Spring Boot 項目中使用就更友善了。

建立 Spring Boot 項目

spring-boot-swagger2

,添加

Web

依賴。之後手動在 pom 檔案中添加 Swagger2 相關的兩個依賴,最終的依賴如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    
    <!-- 1.5.21版本覆寫預設的1.5.20版本,解決@ApiModelProperty的example預設值類型轉換異常BUG - java.lang.NumberFormatException: For input string: "" -->
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.21</version>
    </dependency>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-models</artifactId>
        <version>1.5.21</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>
           

2 Swagger2 配置

新增

Swagger2Config

配置類,如下:

@Configuration
@EnableSwagger2 // 啟用 Swagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cxy35.sample.springboot.swagger2.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("這是網站的标題...")
                        .description("這是網站的描述...")
                        .version("v1.0")
                        .contact(new Contact("這是聯系人名稱", "https://cxy35.com", "[email protected]"))
                        .license("這是網站使用的協定...")
                        .licenseUrl("https://www.baidu.com")
                        .build());
    }
}
           

啟動項目,通路 http://127.0.0.1:8080/swagger-ui.html(老版本) 或 http://127.0.0.1:8080/swagger-ui/(新版本),檢視效果如下:

Spring Boot 整合 Swagger2
注:在新版本中,支援在配置檔案中完成一些配置,比如:

springfox.documentation.enabled

配置可以控制是否啟用 Swagger 文檔生成功能(一般在開發環境開啟,在生産環境關閉)。
#springfox.documentation.enabled=false
           

其他配置如下:

Spring Boot 整合 Swagger2

3 使用

新增

UserController

測試接口,如下:

@RestController
@Api(tags = "使用者管理接口")
public class UserController {
    @GetMapping("/user")
    @ApiOperation(value = "查詢使用者", notes = "根據使用者id查詢使用者")
    @ApiImplicitParam(name = "id", value = "使用者id", required = true, defaultValue = "99")
    public User getUserById(Integer id) {
        User user = new User();
        user.setId(id);
        user.setUsername("cxy35");
        user.setAddress("HZ");
        return user;
    }

    @PutMapping("/user")
    @ApiOperation(value = "更新使用者", notes = "根據使用者id更新使用者名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者id", required = true, defaultValue = "99"),
            @ApiImplicitParam(name = "username", value = "使用者名", required = true, defaultValue = "cxy35")
    })
    // @ApiIgnore
    public User updateUsernameById(String username, Integer id) {
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        return user;
    }

    @PostMapping("/user")
    @ApiOperation(value = "添加使用者", notes = "添加使用者接口")
    public User addUser(@RequestBody User user) {
        return user;
    }

    @DeleteMapping("/user/{id}")
    @ApiOperation(value = "删除使用者", notes = "根據使用者id删除使用者")
    @ApiImplicitParam(name = "id", value = "使用者id", required = true, defaultValue = "99")
    @ApiResponses({
            @ApiResponse(code = 200, message = "删除成功"),
            @ApiResponse(code = 500, message = "删除失敗")
    })
    public void deleteUserById(@PathVariable Long id) {

    }

    @GetMapping("/hello")
    public String hello(String name) {
        return "hello " + name + " !";
    }
}
           

注解說明:

  • @Api

    注解:用來描述一個 Controller 類。
  • @ApiOperation

    注解:用來描述一個接口。
  • @ApiImplicitParam

    注解:用來描述一個參數,可以配置參數的中文含義,也可以給參數設定預設值,這樣在接口測試的時候可以避免手動輸入。
  • @ApiImplicitParams

    注解:如果有多個參數,則需要使用多個 @ApiImplicitParam 注解來描述,多個 @ApiImplicitParam 注解需要放在一個 @ApiImplicitParams 中。
  • 需要注意的是, @ApiImplicitParam 注解中雖然可以指定參數是必填的,但是卻不能代替 @RequestParam(required = true) ,前者的必填隻是在 Swagger2 架構内必填,抛棄了 Swagger2 ,這個限制就沒用了,是以假如開發者需要指定一個參數必填, @RequestParam(required = true) 注解還是不能省略。
  • 如果參數是一個對象(例如上文的 addUser 接口),對于參數的描述也可以放在實體類中,比如:
@ApiModel(value = "使用者實體類",description = "使用者資訊描述類")
public class User {
    @ApiModelProperty(value = "使用者id")
    private Integer id;
    @ApiModelProperty(value = "使用者名")
    private String username;
    @ApiModelProperty(value = "使用者位址")
    private String address;

    // getter/setter
}
           

注解說明:

  • @ApiModel

    注解:用來描述一個實體類。
  • @ApiModelProperty

    注解:用來描述一個實體類的字段。

重新啟動項目,通路 http://127.0.0.1:8080/swagger-ui.html(老版本) 或 http://127.0.0.1:8080/swagger-ui/(新版本),檢視效果如下:

Spring Boot 整合 Swagger2
Spring Boot 整合 Swagger2
Spring Boot 整合 Swagger2
Spring Boot 整合 Swagger2
Spring Boot 整合 Swagger2

4 Spring Security 中的配置

如果項目中內建了 Spring Security ,預設情況下 Swagger2 文檔可能會被攔截,需要在 Spring Security 的配置類中重寫 configure 方法,增加如下過濾配置:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers("/swagger-ui.html")
            .antMatchers("/v2/**")
            .antMatchers("/swagger-resources/**");
}
           
  • Spring Boot 教程合集(微信左下方閱讀全文可直達)。
  • Spring Boot 教程合集示例代碼:https://github.com/cxy35/spring-boot-samples
  • 本文示例代碼:https://github.com/cxy35/spring-boot-samples/tree/master/spring-boot-swagger2

掃碼關注微信公衆号 程式員35 ,擷取最新技術幹貨,暢聊 #程式員的35,35的程式員# 。獨立站點:https://cxy35.com

Spring Boot 整合 Swagger2

繼續閱讀