[springboot 開發單體web shop] 4. Swagger生成Javadoc


Swagger生成JavaDoc


在日常的工作中,特別是現在前后端分離模式之下,接口的提供造成了我們前后端開發人員的溝通
成本大量提升,因為溝通不到位,不及時而造成的[撕幣]事件都成了日常工作。特別是很多的開發人員
不擅長溝通,造成的結果就會讓自己特別的痛苦,也讓合作人員的牙根癢癢。
為了結束戰火蔓延,同時為了提升開發人員的滿意度,Swagger應運而生。

什么是Swagger


Swagger for Everyone
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset.
Swagger open source and pro tools have helped millions of API developers, teams, and organizations deliver great APIs.

簡言之就是指使用工具集簡化用戶、團隊和企業的API開發。

集成Swagger


系統中我選擇使用的是swagger-spring-boot-starter

該項目主要利用Spring Boot的自動化配置特性來實現快速的將swagger2引入spring boot應用來生成API文檔,簡化原生使用swagger2的整合代碼。
看得出來,我在教大家使用的都是在偷懶哦,這可不是什么好現象。。。

添加依賴

        <!--整合Swagger2-->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>

點擊版本號進入swagger-spring-boot-starter/1.9.0.RELEASE/swagger-spring-boot-starter-1.9.0.RELEASE.pom,可以看到它依賴的版本信息。

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.java>1.8</version.java>
        <version.swagger>2.9.2</version.swagger>
        <version.spring-boot>1.5.10.RELEASE</version.spring-boot>
        <version.lombok>1.18.6</version.lombok>
    </properties>

啟用功能

在我們的啟動類ApiApplication上增加@EnableSwagger2Doc注解

@SpringBootApplication
@MapperScan(basePackages = "com.liferunner.mapper")
@ComponentScan(basePackages = {"com.liferunner", "org.n3r.idworker"})
@EnableSwagger2Doc //啟動Swagger
public class ApiApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(ApiApplication.class)
                .run(args);
    }

    @Autowired
    private CORSConfig corsConfig;

    /**
     * 注冊跨域配置信息
     *
     * @return {@link CorsFilter}
     */
    @Bean
    public CorsFilter corsFilter() {
        val corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin(this.corsConfig.getAllowOrigin());
        corsConfiguration.addAllowedMethod(this.corsConfig.getAllowedMethod());
        corsConfiguration.addAllowedHeader(this.corsConfig.getAllowedHeader());
        corsConfiguration.setAllowCredentials(this.corsConfig.getAllowCredentials());

        val urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

配置基礎信息

可以通過properties文件和yml/yaml文件配置。

# 配置swagger2
swagger:
  enabled: true #是否啟用swagger,默認:true
  title: 實戰電商api平台
  description: provide 電商 API
  version: 1.0.0.RC
  license: Apache License, Version 2.0
  license-url: https://www.apache.org/licenses/LICENSE-2.0.html
  terms-of-service-url: http://www.life-runner.com
  contact:
    email: magicianisaac@gmail.com
    name: Isaac-Zhang
    url: http://www.life-runner.com
  base-package: com.liferunner
  base-path: /**

階段效果一

運行我們的api項目,在瀏覽器輸入:http://localhost:8088/swagger-ui.html,可以看到如下:
階段效果1
可以看到,我們在yml文件中配置的信息,展示在了頁面的頂部,點擊用戶管理:
用戶管理
從上圖可以看出,我們的/users/create接口展出出來,並且要傳入的參數,請求類型等等信息都已經展示在上圖中。
但是,要傳遞的參數是什么意思,都是我們的字段信息,我們要如何讓它更友好的展示給調用方呢?讓我們繼續
完善我們的文檔信息:

完善說明信息

在我們創建用戶的時候,需要傳遞一個com.liferunner.dto.UserRequestDTO對象,這個對象的屬性如下:

@RestController
@RequestMapping(value = "/users")
@Slf4j
@Api(tags = "用戶管理")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "用戶詳情", notes = "查詢用戶")
    @ApiIgnore
    @GetMapping("/get/{id}")
    //@GetMapping("/{id}") 如果這里設置位這樣,每次請求swagger都會進到這里,是一個bug
    public String getUser(@PathVariable Integer id) {
        return "hello, life.";
    }

    @ApiOperation(value = "創建用戶", notes = "用戶注冊接口")
    @PostMapping("/create")
    public JsonResponse createUser(@RequestBody UserRequestDTO userRequestDTO) {
        //...
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(value = "創建用戶DTO", description = "用戶注冊需要的參數對象")
public class UserRequestDTO {
    @ApiModelProperty(value = "用戶名", notes = "username", example = "isaaczhang", required = true)
    private String username;
    @ApiModelProperty(value = "注冊密碼", notes = "password", example = "12345678", required = true)
    private String password;
    @ApiModelProperty(value = "確認密碼", notes = "confimPassword", example = "12345678", required = true)
    private String confirmPassword;
}

可以看到,我們有很多通過@Apixxx開頭的注解說明,這個就是Swagger提供給我們用以說明字段和文檔說明的注解。

  • @Api 表示對外提供API
  • @ApiIgnore 表示不對外展示,可用於類和方法
  • @ApiOperation 就是指的某一個API下面的CURD動作
  • @ApiResponses 描述操作可能出現的異常情況
  • @ApiParam 描述傳遞的單參數信息
  • @ApiModel 用來描述java object的屬性說明
  • @ApiModelProperty 描述object 字段說明
    所有的使用,都可以進入到相關的注解的具體class去查看所有的屬性信息,都比較簡單,這里就不做具體描述了。想要查看更多的屬性說明,
    大家可以進入:Swagger屬性說明傳送門

配置完之后,重啟應用,刷新UI頁面:
階段效果二
上圖中紅框圈定的都是我們重新配置的說明信息,足夠簡單明了吧~

集成更好用的UI界面

針對於API說明來說,我們上述的信息已經足夠優秀了,可是做技術,我們應該追求的是更加極致的地步,上述的UI界面在我們提供大批量
用戶接口的時候,友好型就有那么一丟丟的欠缺了,現在給大家再介紹一款更好用的開源Swagger UI,有請swagger-bootstrap-ui
UI2
我們從上圖可以看到,這個UI的Star數目已經超過1.1K了,這就證明它已經很優秀了,我們接下來解開它的廬山真面目吧。

集成依賴

只需要在我們的expensive-shop\pom.xml中加入以下依賴代碼:

        <!--一種新的swagger ui-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.6</version>
        </dependency>

預覽效果

添加完依賴后,只需要重啟我們的應用,然后訪問http://localhost:8088/doc.html,效果如下:
階段效果3
點擊創建用戶:
階段效果4
上述的效果是不是更符合我們的審美了~
到此為止,我們使用Swagger來動態生成API的效果已經全部演示完了,但是如果某一天我們要和一個不能連接查看我們網站的客戶進行集成的時候,我們怎么辦呢?
還是要手寫一份文檔給他們嗎? 那我們不就一樣很痛苦嗎!!!
作為程序員,我們是絕對不能允許這種情況發生的!
那就讓我們繼續看下去。

生成離線文檔

為了不讓我們做痛苦的工作,我們既然已經在代碼中添加了那么多的說明信息,是否有一種方式可以幫助我們來生成一份離線的文檔呢?答案是肯定的。

開源項目swagger2markup

A Swagger to AsciiDoc or Markdown converter to simplify the generation of an up-to-date RESTful API documentation by combining documentation that’s been hand-written with auto-generated API documentation.

源碼傳送門
documents傳送門

Swagger2Markup它主要是用來將Swagger自動生成的文檔轉換成幾種流行的格式以便離線使用
格式:AsciiDoc、HTML、Markdown、Confluence

使用MAVEN插件生成AsciiDoc文檔

mscx-shop-api\pom.xml中加入以下依賴代碼:

<build>
        <plugins>
            <!--生成 AsciiDoc 文檔(swagger2markup)-->
            <plugin>
                <groupId>io.github.swagger2markup</groupId>
                <artifactId>swagger2markup-maven-plugin</artifactId>
                <version>1.3.3</version>
                <configuration>
                    <!--這里是要啟動我們的項目,然后抓取api-docs的返回結果-->
                    <swaggerInput>http://localhost:8088/v2/api-docs</swaggerInput>
                    <outputDir>src/docs/asciidoc/generated-doc</outputDir>
                    <config>
                        <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
                    </config>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • <swaggerInput>http://localhost:8088/v2/api-docs</swaggerInput> 是為了獲取我們的api JSON數據,如下圖:
    API-JSON
  • <outputDir>src/docs/asciidoc/generated-doc</outputDir> 設置我們要生成的目錄地址

執行命令:

expensive-shop\mscx-shop-api>mvn swagger2markup:convertSwagger2markup

要是大家覺得命令太長了,也可以點擊IDEA => Maven => mscx-shop-api => Plugins => swagger2markup => swagger2markup:convertSwagger2markup 就可以執行啦,如下圖:
swagger2markup
生成結果如下:
asciidoc
adoc文件生成好了,那么我們使用它來生成html吧

使用MAVEN插件生成HTML

mscx-shop-api\pom.xml中加入以下依賴代碼:

            <!--生成 HTML 文檔-->
            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.6</version>
                <configuration>
                    <sourceDirectory>src/docs/asciidoc/generated-doc</sourceDirectory>
                    <outputDirectory>src/docs/asciidoc/html</outputDirectory>
                    <backend>html</backend>
                    <sourceHighlighter>coderay</sourceHighlighter>
                    <attributes>
                        <toc>left</toc>
                    </attributes>
                </configuration>
            </plugin>
  • <sourceDirectory>src/docs/asciidoc/generated-doc</sourceDirectory> 源文件目錄指定為我們上一節生成的adoc
  • <outputDirectory>src/docs/asciidoc/html</outputDirectory> 指定輸出目錄

執行生成命令:

\expensive-shop\mscx-shop-api>mvn asciidoctor:process-asciidoc

生成結果如下:
result html
打開overview.html,如下:
html

至此,我們的文檔就已經全部生成了!

下節預告


下一節我們將繼續開發我們的用戶登錄以及首頁信息的部分展示,在過程中使用到的任何開發組件,我都會通過專門的一節來進行介紹的,兄弟們末慌!

gogogo!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM