Swagger 文檔工具 設計、構建、文檔化和使用您的 RESTful API

Swagger

Swagger 是一個功能強大的開源框架,支持大量工具生態系統,幫助您設計、構建、文檔化和使用您的 RESTful API。

使用 SpringBoot

您可以從 swagger-springboot 獲取完整的項目演示。

springboot-blog 中文版

文件結構可能如下所示:

.
|____main
| |____java
| | |____com
| | | |____ryo
| | | | |____Application.java
| | | | |____controller
| | | | | |____HelloWorld.java
| | | | |____Swagger2.java
| |____resources
| | |____application.properties
| | |____log4j2.xml
| | |____README.md

maven 配置

1、 創建 SpringBoot 項目

  • pom.xml 中導入 SpringBoot 依賴包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ryo</groupId>
    <artifactId>springboot</artifactId>
    <version>1.0.0</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <plugin.tomcat.version>2.2</plugin.tomcat.version>
        <maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
        <maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>

        <!--spring-boot-->
        <spring-boot.version>1.3.5.RELEASE</spring-boot.version>

        <log4j.version>2.6</log4j.version>
    </properties>

    <dependencies>
        <!--spring-boot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${spring-boot.version}</version>
        </dependency>

        <!--log4j-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <skipTests>true</skipTests>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2、maven 導入 jar

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
</dependency>

配置信息

我們可以定義一個 swagger 的全局配置。

package com.github.houbb.register.http.admin.config;

import org.springframework.context.annotation.Bean;
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;

/**
 * swagger 配置
 *
 * @author binbin.hou
 * @since 1.0.0
 */
@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.github.houbb.register.http.admin.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger測試")
                        .description("SpringBoot整合Swagger,詳細信息......")
                        .version("9.0")
                        .contact(new Contact("老馬", "blog.csdn.net", "[email protected]"))
                        .license("The Apache License")
                        .licenseUrl("http://www.baidu.com")
                        .build());
    }

}

最核心的主要是 RequestHandlerSelectors.basePackage("com.github.houbb.register.http.admin.controller")

我們指定了需要掃描的包路徑。

文檔定義

3、配置使用

  • Application.java
package com.ryo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by houbinbin on 16/6/5.
 */
@SpringBootApplication
public class Application {
    public static void main(String args[]) {
        SpringApplication.run(Application.class, args);
    }
}
  • HelloWorld.java
package com.ryo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by houbinbin on 16/6/19.
 */
@RestController
@RequestMapping("hello")
@Api(value = "hello", description = "spring boot 初步測試")
public class HelloWorld {

    @ApiOperation(value="hello", notes="初步使用啦啦啦")
    @RequestMapping(method = RequestMethod.GET)
    public String hello() {
        return "SUCCESS";
    }
}
  • application.properties
server.port=180080

應用啓動 & 訪問

4、 啓動應用

Maven Projects->${project}->Plugins->spring-boot->spring-boot:run

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.5.RELEASE)

2016-12-25 15:29:50.066  INFO 4095 --- [           main] com.ryo.Application                      : Starting Application on houbinbindeMacBook-Pro.local with PID 4095 (/Users/houbinbin/IT/code/springboot/target/classes started by houbinbin in /Users/houbinbin/IT/code/springboot)
2016-12-25 15:29:50.069  INFO 4095 --- [           main] com.ryo.Application                      : No active profile set, falling back to default profiles: default
...
2016-12-25 15:29:52.688  INFO 4095 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 18080 (http)
2016-12-25 15:29:52.692  INFO 4095 --- [           main] com.ryo.Application                      : Started Application in 3.094 seconds (JVM running for 5.262)
  • 瀏覽器訪問

瀏覽器訪問:http://localhost:8080/swagger-ui.html

基本配置例子

Controller 控制器

package com.github.houbb.register.http.admin.controller;


import com.github.houbb.register.http.admin.model.ClientLogDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 客戶端數據日誌 前端控制器
 * </p>
 *
 * @author binbin.hou
 * @since 2021-03-08
 */
@Controller
@RequestMapping("/clientLog")
@Api(tags = "客戶端日誌 CRUD")
public class ClientLogController {

    @PostMapping("/add")
    @ApiOperation("添加日誌")
    @ResponseBody
    public String add(ClientLogDto clientLogDto) {
        System.out.println(clientLogDto);
        return "ok";
    }

}

實體屬性

針對入參 ClientLogDto,我們可以添加對應的屬性描述如下:

public class ClientLogDto implements Serializable {

    @ApiModelProperty(value = "類型")
    private String type;

    @ApiModelProperty(value = "地址")
    private String ip;

    @ApiModelProperty(value = "名稱")
    private String name;

    //getter & setter & toString()
}

效果

重新啓動應用,效果如下:

輸入圖片說明

測試

我們可以使用 【Try it out】,可以進行相關的測試。

輸入圖片說明

點擊 execute 按鈕,可以獲取非常詳細的文檔返回。

常用註解說明

  1. @Api註解可以用來標記當前Controller的功能。

  2. @ApiOperation註解用來標記一個方法的作用。

  3. @ApiImplicitParam註解用來描述一個參數,可以配置參數的中文含義,也可以給參數設置默認值,這樣在接口測試的時候可以避免手動輸入。

  4. 如果有多個參數,則需要使用多個@ApiImplicitParam註解來描述,多個@ApiImplicitParam註解需要放在一個@ApiImplicitParams註解中。

  5. 需要注意的是,@ApiImplicitParam註解中雖然可以指定參數是必填的,但是卻不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架內必填,拋棄了Swagger2,這個限制就沒用了,所以假如開發者需要指定一個參數必填,@RequestParam(required = true)註解還是不能省略。

  6. 如果參數是一個對象(例如上文的更新接口),對於參數的描述也可以放在實體類中。

一點思考

swagger2 的 ui 還是非常舒服的,功能也比較強大,不過有一點比較可惜,那就是註解顯得有一點點冗餘。

可以考慮配合 yAPI 使用。

參考資料

SpringBoot的整合(四、整合Swagger2)

SpringBoot swagger 配置賬號密碼

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