007--【SpringBoot】整合Swagger2.0

1迹卢、Swagger簡介

使用Swagger,就是把相關(guān)的信息存儲在它定義的描述文件里面(yml或json格式),再通過維護這個描述文件可以去更新接口文檔搓逾,以及生成各端代碼

簡而言之:代碼即接口文檔轮听,接口文檔即代碼

2骗露、參考網(wǎng)址

3、項目整合

3.1 Maven配置

先吐槽:不知道在哪搞了個maven鏡像血巍,下載的版本一致都不對萧锉,沒有Swagger相關(guān)的標注,折騰了好久

<?xml version="1.0" encoding="UTF-8"?>

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <localRepository>C:/Users/zhifeng/.m2/repository/</localRepository>
    <pluginGroups>
    </pluginGroups>
    <proxies>
    </proxies>
    <servers>
    </servers>
    <mirrors>
        <mirror>
          <id>alimaven</id>
          <name>aliyun maven</name>
          <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
          <mirrorOf>central</mirrorOf>        
        </mirror>
    </mirrors>
    <profiles>
        <profile>
            <id>nexus</id>
            <repositories>
                <repository>
                    <id>central</id>
                    <url>http://maven.aliyun.com/nexus/content/repositories/central</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                </repository>
                <repository>
                    <id>ansj-repo</id>
                    <name>ansj Repository</name>
                    <url>http://maven.nlpcn.org/</url>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                </repository>
            </repositories>
        </profile>
    </profiles>
    <activeProfiles>
        <activeProfile>nexus</activeProfile>
    </activeProfiles>
</settings>

3.2 Swagger2.0整合

先導入pom依賴述寡,然后配置SwaggerConfig柿隙,最后在Controller上添加標注,最后訪問網(wǎng)址:http://localhost:9090/swagger-ui.html

  • 先導入pom依賴
        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>
  • 配置SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        ticketPar.name("Authorization").description("token")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(true).build(); //header中的ticket參數(shù)非必填鲫凶,傳空也可以
        pars.add(ticketPar.build());    //根據(jù)每個方法名也知道當前方法在設置什么參數(shù)

        return new Docket(DocumentationType.SWAGGER_2)//文檔類型:DocumentationType.SWAGGER_2
                .apiInfo(apiInfo())//api信息
                .select()//構(gòu)建api選擇器
                .apis(RequestHandlerSelectors.basePackage("com.enzoism.controller"))//配置為Controller層的路徑
                .paths(PathSelectors.any())//api選擇器選擇包路徑下任何api顯示在文檔中禀崖,根據(jù)需要配置所有還是用正則過濾
                .build();//創(chuàng)建文檔
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("標題")
                .description("描述")
                .termsOfServiceUrl("地址")
                .version("1.0")
                .build();
    }
}
  • controller添加標注
    @GetMapping("user/{id}")
    @ApiOperation(value="getUserMessage", notes="根據(jù)ID獲取用戶信息!")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "String", paramType = "path")
    public User getUserById(@PathVariable String id){
        User user = userService.getUserById(id);
        return user;
    }

4 多環(huán)境配置

以上的接口暴露會產(chǎn)生一個問題,如果在生產(chǎn)環(huán)境怎么屏蔽該地址掀序?

  • 4.1使用標識進行開關(guān)控制
  • 4.2 針對不同的環(huán)境使用不同的application.propertites配置如下
### Swagger開發(fā)
swagger2.enable=false
  • 4.3 訪問失敗

5帆焕、文檔導出

接口的意義是文檔,如果不能進行文檔導出,貌似意義不是很大叶雹,只能是接口調(diào)用而已

  • 5.1 新建工程财饥,添加依賴
        <!-- swagger-文檔導出 -->
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>ch.netzwerg</groupId>
            <artifactId>paleo-core</artifactId>
            <version>0.10.2</version>
        </dependency>
        <dependency>
            <groupId>io.vavr</groupId>
            <artifactId>vavr</artifactId>
            <version>0.9.2</version>
        </dependency>
  • 創(chuàng)建一個測試類
package com.enzoism;

import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;
import java.nio.file.Paths;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SpringbootApplicationTests {

    /**
     * 生成AsciiDocs格式文檔
     * @throws Exception
     */
    @Test
    public void generateAsciiDocs() throws Exception {
        //    輸出Ascii格式
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:9090/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFolder(Paths.get("./docs/asciidoc/generated"));
    }

    /**
     * 生成Markdown格式文檔
     * @throws Exception
     */
    @Test
    public void generateMarkdownDocs() throws Exception {
        //    輸出Markdown格式
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:9090/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFolder(Paths.get("./docs/markdown/generated"));
    }
    /**
     * 生成AsciiDocs格式文檔,并匯總成一個文件
     * @throws Exception
     */
    @Test
    public void generateAsciiDocsToFile() throws Exception {
        //    輸出Ascii到單文件
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:9090/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFile(Paths.get("./docs/asciidoc/generated/all"));
    }

    /**
     * 生成Markdown格式文檔,并匯總成一個文件
     * @throws Exception
     */
    @Test
    public void generateMarkdownDocsToFile() throws Exception {
        //    輸出Markdown到單文件
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:9090/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFile(Paths.get("./docs/markdown/generated/all"));
    }
    /**
   * 生成Confluence格式文檔
   * @throws Exception
   */
  @Test
  public void generateConfluenceDocs() throws Exception {
      //    輸出Confluence使用的格式
      Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
              .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
              .withOutputLanguage(Language.ZH)
              .withPathsGroupedBy(GroupBy.TAGS)
              .withGeneratedExamples()
              .withoutInlineSchema()
              .build();

      Swagger2MarkupConverter.from(new URL("http://localhost:9090/v2/api-docs"))
              .withConfig(config)
              .build()
              .toFolder(Paths.get("./docs/confluence/generated"));
  }
}
  • 5.3 直接運行測試接口

如果生成PDF并解決亂碼,可以參考:http://www.reibang.com/p/3441289c7afc


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末折晦,一起剝皮案震驚了整個濱河市钥星,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌满着,老刑警劉巖谦炒,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機殴瘦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門同诫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了谜喊?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長倦始。 經(jīng)常有香客問我斗遏,道長,這世上最難降的妖魔是什么鞋邑? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任诵次,我火速辦了婚禮,結(jié)果婚禮上炫狱,老公的妹妹穿的比我還像新娘藻懒。我一直安慰自己,他們只是感情好视译,可當我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布嬉荆。 她就那樣靜靜地躺著,像睡著了一般酷含。 火紅的嫁衣襯著肌膚如雪鄙早。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天椅亚,我揣著相機與錄音限番,去河邊找鬼。 笑死呀舔,一個胖子當著我的面吹牛弥虐,可吹牛的內(nèi)容都是我干的扩灯。 我是一名探鬼主播,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼霜瘪,長吁一口氣:“原來是場噩夢啊……” “哼珠插!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起颖对,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤捻撑,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后缤底,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體顾患,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年个唧,在試婚紗的時候發(fā)現(xiàn)自己被綠了江解。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡坑鱼,死狀恐怖膘流,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鲁沥,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布耕魄,位于F島的核電站画恰,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏吸奴。R本人自食惡果不足惜允扇,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望则奥。 院中可真熱鬧考润,春花似錦、人聲如沸读处。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽罚舱。三九已至井辜,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間管闷,已是汗流浹背粥脚。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留包个,地道東北人刷允。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親树灶。 傳聞我的和親對象是個殘疾皇子纤怒,可洞房花燭夜當晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內(nèi)容