SpringBoot入門篇3 -- 整合Swagger

寫在前面

距離上一次分享整合SpringBoot過去了大半年了,時(shí)光荏苒捧杉,今天將繼續(xù)更新SpringBoot的相關(guān)技術(shù)點(diǎn)。

Swagger

這里品山,我就不過多介紹Swagger是什么了述雾,相信你看這文章的時(shí)候也是有了解Swagger的相關(guān)概念的吼鱼。簡(jiǎn)單的說,Swagger就是一種定義接口信息的規(guī)范绰咽。具體可以參見Swagger官網(wǎng)(https://swagger.io

SpringBoot整合Swagger

下面分享一下SpringBoot整合Swagger的內(nèi)容菇肃,看一下如何在一個(gè)既有的SpringBoot工程下整合Swagger。

SpringBoot初始工程

啟動(dòng)類 SpringbootSwaggerApplication.java

package top.flygrk.ishare.springbootswagger;

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

@SpringBootApplication
public class SpringbootSwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootSwaggerApplication.class, args);
    }

}

實(shí)體類 User.java

注意:這里采用lombok插件及注解

package top.flygrk.ishare.springbootswagger.entity;

import lombok.Data;

/**
 * @Package top.flygrk.ishare.springbootswagger.entity
 * @Author wuzy
 * @Date 2019/8/5 11:05
 * @Version V1.0
 * @Description:
 */
@Data
public class User {
    private String id;
    private String username;
    private int age;
    private String note;
}

接口類 UserController.java

我們這里有2個(gè)api接口:插入用戶insert和根據(jù)用戶id查詢用戶信息取募。這里均采用模擬的方式琐谤,無service及dao層的處理邏輯。

package top.flygrk.ishare.springbootswagger.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import top.flygrk.ishare.springbootswagger.entity.User;

/**
 * @Package top.flygrk.ishare.springbootswagger.controller
 * @Author wuzy
 * @Date 2019/8/5 11:07
 * @Version V1.0
 * @Description: 用戶接口
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
    * @Authod wuzy
    * @Date 2019/8/5 11:09
    * @Method insert
    * @Param    user
    * @ReturnType Object
    * @Description: 插入用戶信息
    */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public Object insert(@RequestBody User user) {
        JSONObject jsonObject = new JSONObject();
        if (user == null) {
            jsonObject.put("result", "failed");
            jsonObject.put("reason", "user is null");
            return jsonObject;
        }
        jsonObject.put("result", "success");
        jsonObject.put("msg", user.getUsername());
        return jsonObject;
    }

    @RequestMapping(value = "findById", method = RequestMethod.GET)
    public Object findById(String id) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isEmpty(id)) {
            jsonObject.put("result", "failed");
            jsonObject.put("reason", "user is null");
            return jsonObject;
        }
        jsonObject.put("id", id);
        jsonObject.put("username", "wuzy");
        jsonObject.put("age", 20);
        jsonObject.put("note", "coding boy");
        return jsonObject;
    }

}

Swagger簡(jiǎn)單使用

我們先來看下如何初步使用Swagger玩敏,最方便的一種斗忌。首先添加maven依賴,然后再引入Swagger的注解即可旺聚。我們來仔細(xì)看看:

引入pom依賴

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

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

添加Swagger注解

我們只需要在啟動(dòng)類SpringbootSwaggerApplication添加注解@EnableSwagger2Doc织阳,即可完成對(duì)Swagger的簡(jiǎn)單整合,是不是so easy!!!

@SpringBootApplication
@EnableSwagger2Doc
public class SpringbootSwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootSwaggerApplication.class, args);
    }

}

驗(yàn)證

我們啟動(dòng)程序砰粹,去驗(yàn)證一下是否可以使用Swagger唧躲。我們通過訪問http://127.0.0.1:9000/swagger-ui.html,可以看到如下界面:

我們?cè)僬归_看下user-controller下的內(nèi)容:


從上圖可以看出碱璃,再user-controller下弄痹,存在兩個(gè)接口,分別為/user/findById 和 /user/insert嵌器。同時(shí)也可以看出其訪問方式為GET/POST信息肛真。我們以 /user/findById為例,來看下其具體內(nèi)容:



我們可以看到其需要的請(qǐng)求參數(shù)為id爽航,類型為String等信息蚓让。并且我們可以使用后面的【Try it out】按鈕,調(diào)用findById接口讥珍。我們來調(diào)用一下試試:

Swagger補(bǔ)充

有沒有覺得上面簡(jiǎn)單的那個(gè)Swagger-UI很難閱讀历极?那么下面,我們繼續(xù)來優(yōu)化下他的提示信息串述,我們通過相關(guān)注解來具體的描述接口的相關(guān)信息执解,比如類的含義、接口的含義纲酗、參數(shù)的含義等信息衰腌,具體代碼如下:

UserController.java

package top.flygrk.ishare.springbootswagger.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import top.flygrk.ishare.springbootswagger.entity.User;

/**
 * @Package top.flygrk.ishare.springbootswagger.controller
 * @Author wuzy
 * @Date 2019/8/5 11:07
 * @Version V1.0
 * @Description: 用戶接口
 */
@RestController
@RequestMapping("user")
@Api("用戶管理模塊")
public class UserController {
    /**
    * @Authod wuzy
    * @Date 2019/8/5 11:09
    * @Method insert
    * @Param    user
    * @ReturnType Object
    * @Description: 插入用戶信息
    */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    @ApiOperation(value = "插入用戶信息", notes = "插入用戶的詳細(xì)信息")
    public Object insert(@RequestBody User user) {
        JSONObject jsonObject = new JSONObject();
        if (user == null) {
            jsonObject.put("result", "failed");
            jsonObject.put("reason", "user is null");
            return jsonObject;
        }
        jsonObject.put("result", "success");
        jsonObject.put("msg", user.getUsername());
        return jsonObject;
    }

    @RequestMapping(value = "findById", method = RequestMethod.GET)
    @ApiOperation(value = "查詢用戶信息", notes = "根據(jù)id查詢用戶信息")
    public Object findById(@ApiParam(value = "用戶id", required = true) String id) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isEmpty(id)) {
            jsonObject.put("result", "failed");
            jsonObject.put("reason", "user is null");
            return jsonObject;
        }
        jsonObject.put("id", id);
        jsonObject.put("username", "wuzy");
        jsonObject.put("age", 20);
        jsonObject.put("note", "coding boy");
        return jsonObject;
    }

}

User.java

package top.flygrk.ishare.springbootswagger.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @Package top.flygrk.ishare.springbootswagger.entity
 * @Author wuzy
 * @Date 2019/8/5 11:05
 * @Version V1.0
 * @Description:
 */
@Data
@ApiModel
public class User {
    @ApiModelProperty(value = "用戶id", required = true, dataType = "String")
    private String id;
    @ApiModelProperty(value = "用戶名", dataType = "String")
    private String username;
    @ApiModelProperty(value = "年紀(jì)", dataType = "int")
    private int age;
    @ApiModelProperty(value = "備注", dataType = "String")
    private String note;
}

進(jìn)行上述修改之后,我們?cè)俅螁?dòng)SpringBoot工程右蕊,打開Swagger-UI,可以看到內(nèi)容如下:


首先吮螺,展開看一下“查詢用戶信息接口”饶囚,可以看出在id后面的Description下有“用戶id”的提示信息:


然后,我們來仔細(xì)看看insert接口的信息:


關(guān)于注解的說明本文暫時(shí)不再敘述鸠补,請(qǐng)大家參閱其他資料萝风。整合Swagger的入門篇就說到這,還有一些其他的注解紫岩,以后再進(jìn)行分享规惰。例如:


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市泉蝌,隨后出現(xiàn)的幾起案子歇万,更是在濱河造成了極大的恐慌,老刑警劉巖勋陪,帶你破解...
    沈念sama閱讀 221,820評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贪磺,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡诅愚,警方通過查閱死者的電腦和手機(jī)寒锚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來违孝,“玉大人壕曼,你說我怎么就攤上這事〉茸牵” “怎么了腮郊?”我有些...
    開封第一講書人閱讀 168,324評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)筹燕。 經(jīng)常有香客問我轧飞,道長(zhǎng),這世上最難降的妖魔是什么撒踪? 我笑而不...
    開封第一講書人閱讀 59,714評(píng)論 1 297
  • 正文 為了忘掉前任过咬,我火速辦了婚禮,結(jié)果婚禮上制妄,老公的妹妹穿的比我還像新娘掸绞。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,724評(píng)論 6 397
  • 文/花漫 我一把揭開白布衔掸。 她就那樣靜靜地躺著烫幕,像睡著了一般。 火紅的嫁衣襯著肌膚如雪敞映。 梳的紋絲不亂的頭發(fā)上较曼,一...
    開封第一講書人閱讀 52,328評(píng)論 1 310
  • 那天,我揣著相機(jī)與錄音振愿,去河邊找鬼捷犹。 笑死,一個(gè)胖子當(dāng)著我的面吹牛冕末,可吹牛的內(nèi)容都是我干的萍歉。 我是一名探鬼主播,決...
    沈念sama閱讀 40,897評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼档桃,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼枪孩!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起胳蛮,我...
    開封第一講書人閱讀 39,804評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤销凑,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后仅炊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體斗幼,經(jīng)...
    沈念sama閱讀 46,345評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,431評(píng)論 3 340
  • 正文 我和宋清朗相戀三年抚垄,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蜕窿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,561評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡呆馁,死狀恐怖桐经,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情浙滤,我是刑警寧澤阴挣,帶...
    沈念sama閱讀 36,238評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站纺腊,受9級(jí)特大地震影響畔咧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜揖膜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,928評(píng)論 3 334
  • 文/蒙蒙 一誓沸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧壹粟,春花似錦拜隧、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽垦页。三九已至,卻和暖如春薇组,著一層夾襖步出監(jiān)牢的瞬間外臂,已是汗流浹背坐儿。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工律胀, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人貌矿。 一個(gè)月前我還...
    沈念sama閱讀 48,983評(píng)論 3 376
  • 正文 我出身青樓炭菌,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親逛漫。 傳聞我的和親對(duì)象是個(gè)殘疾皇子黑低,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,573評(píng)論 2 359