宅男在线永久免费观看网直播,亚洲欧洲日产国码无码久久99,野花社区在线观看视频,亚洲人交乣女bbw,一本一本久久a久久精品综合不卡

全部
常見問題
產(chǎn)品動態(tài)
精選推薦

Spring Boot 2.x基礎(chǔ)教程:使用Swagger2構(gòu)建強大的API文檔

管理 管理 編輯 刪除

隨著前后端分離架構(gòu)和微服務(wù)架構(gòu)的流行,我們使用Spring Boot來構(gòu)建RESTful API項目的場景越來越多。通常我們的一個RESTful API就有可能要服務(wù)于多個不同的開發(fā)人員或開發(fā)團隊:IOS開發(fā)、Android開發(fā)、Web開發(fā)甚至其他的后端服務(wù)等。為了減少與其他團隊平時開發(fā)期間的頻繁溝通成本,傳統(tǒng)做法就是創(chuàng)建一份RESTful API文檔來記錄所有接口細節(jié),然而這樣的做法有以下幾個問題:

  • 由于接口眾多,并且細節(jié)復(fù)雜(需要考慮不同的HTTP請求類型、HTTP頭部信息、HTTP請求內(nèi)容等),高質(zhì)量地創(chuàng)建這份文檔本身就是件非常吃力的事,下游的抱怨聲不絕于耳。
  • 隨著時間推移,不斷修改接口實現(xiàn)的時候都必須同步修改接口文檔,而文檔與代碼又處于兩個不同的媒介,除非有嚴格的管理機制,不然很容易導致不一致現(xiàn)象。

為了解決上面這樣的問題,本文將介紹RESTful API的重磅好伙伴Swagger2,它可以輕松的整合到Spring Boot中,并與Spring MVC程序配合組織出強大RESTful API文檔。它既可以減少我們創(chuàng)建文檔的工作量,同時說明內(nèi)容又整合入實現(xiàn)代碼中,讓維護文檔和修改代碼整合為一體,可以讓我們在修改代碼邏輯的同時方便的修改文檔說明。另外Swagger2也提供了強大的頁面測試功能來調(diào)試每個RESTful API。具體效果如下圖所示:

c6317202412161004523730.png

下面來具體介紹,在Spring Boot中使用我們自己實現(xiàn)的starter來整合Swagger。

準備工作

首先,我們需要一個Spring Boot實現(xiàn)的RESTful API工程,若您沒有做過這類內(nèi)容,建議先閱讀上一篇教程: 構(gòu)建RESTful API與單元測試構(gòu)建一個。

整合Swagger2

第一步:添加swagger-spring-boot-starter依賴

pom.xml中加入依賴,具體如下:


    com.spring4all
    swagger-spring-boot-starter
    1.9.0.RELEASE

第二步:應(yīng)用主類中添加@EnableSwagger2Doc注解,具體如下

@EnableSwagger2Doc
@SpringBootApplication
public class Chapter22Application {

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

}

第三步application.properties中配置文檔相關(guān)內(nèi)容,比如

swagger.title=spring-boot-starter-swagger
swagger.description=Starter for swagger 2.x
swagger.version=1.4.0.RELEASE
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=didi
swagger.contact.url=https://blog.didispace.com
[email protected]
swagger.base-package=com.didispace
swagger.base-path=/**

各參數(shù)配置含義如下:

  • swagger.title:標題
  • swagger.description:描述
  • swagger.version:版本
  • swagger.license:許可證
  • swagger.licenseUrl:許可證URL
  • swagger.termsOfServiceUrl:服務(wù)條款URL
  • swagger.contact.name:維護人
  • swagger.contact.url:維護人URL
  • swagger.contact.email:維護人email
  • swagger.base-package:swagger掃描的基礎(chǔ)包,默認:全掃描
  • swagger.base-path:需要處理的基礎(chǔ)URL規(guī)則,默認:/**

第四步:啟動應(yīng)用,訪問:http://localhost:8080/swagger-ui.html,就可以看到如下的接口文檔頁面:

885ac202412161006312209.png

添加文檔內(nèi)容

在整合完Swagger之后,在http://localhost:8080/swagger-ui.html頁面中可以看到,關(guān)于各個接口的描述還都是英文或遵循代碼定義的名稱產(chǎn)生的。這些內(nèi)容對用戶并不友好,所以我們需要自己增加一些說明來豐富文檔內(nèi)容。如下所示,我們通過@Api@ApiOperation注解來給API增加說明、通過@ApiImplicitParam、@ApiModel、@ApiModelProperty注解來給參數(shù)增加說明。

比如下面的例子:

@Api(tags = "用戶管理")
@RestController
@RequestMapping(value = "/users")     // 通過這里配置使下面的映射都在/users下
public class UserController {

    // 創(chuàng)建線程安全的Map,模擬users信息的存儲
    static Map users = Collections.synchronizedMap(new HashMap<>());

    @GetMapping("/")
    @ApiOperation(value = "獲取用戶列表")
    public List getUserList() {
        List r = new ArrayList<>(users.values());
        return r;
    }

    @PostMapping("/")
    @ApiOperation(value = "創(chuàng)建用戶", notes = "根據(jù)User對象創(chuàng)建用戶")
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "獲取用戶詳細信息", notes = "根據(jù)url的id來獲取用戶詳細信息")
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @PutMapping("/{id}")
    @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "用戶編號", required = true, example = "1")
    @ApiOperation(value = "更新用戶詳細信息", notes = "根據(jù)url的id來指定更新對象,并根據(jù)傳過來的user信息來更新用戶詳細信息")
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "刪除用戶", notes = "根據(jù)url的id來指定刪除對象")
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}

@Data
@ApiModel(description="用戶實體")
public class User {

    @ApiModelProperty("用戶編號")
    private Long id;
    @ApiModelProperty("用戶姓名")
    private String name;
    @ApiModelProperty("用戶年齡")
    private Integer age;

}

完成上述代碼添加后,啟動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html,就能看到下面這樣帶中文說明的文檔了(其中標出了各個注解與文檔元素的對應(yīng)關(guān)系以供參考):

e26e6202412161007048708.png

e671e2024121610071031.png

API文檔訪問與調(diào)試

在上圖請求的頁面中,我們看到user的Value是個輸入框?是的,Swagger除了查看接口功能外,還提供了調(diào)試測試功能,我們可以點擊上圖中右側(cè)的Model Schema(黃色區(qū)域:它指明了User的數(shù)據(jù)結(jié)構(gòu)),此時Value中就有了user對象的模板,我們只需要稍適修改,點擊下方“Try it out!”按鈕,即可完成了一次請求調(diào)用!

此時,你也可以通過幾個GET請求來驗證之前的POST請求是否正確。

相比為這些接口編寫文檔的工作,我們增加的配置內(nèi)容是非常少而且精簡的,對于原有代碼的侵入也在忍受范圍之內(nèi)。因此,在構(gòu)建RESTful API的同時,加入Swagger來對API文檔進行管理,是個不錯的選擇。


注:本文轉(zhuǎn)載自“程序猿DD”,如有侵權(quán),請聯(lián)系刪除!

請登錄后查看

哈哈哈醬 最后編輯于2024-12-18 14:57:40

快捷回復(fù)
回復(fù)
回復(fù)
回復(fù)({{post_count}}) {{!is_user ? '我的回復(fù)' :'全部回復(fù)'}}
排序 默認正序 回復(fù)倒序 點贊倒序

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level || item.bbs_level }}

作者 管理員 企業(yè)

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推薦': '推薦'}}
{{item.is_suggest == 1? '取消推薦': '推薦'}}
沙發(fā) 板凳 地板 {{item.floor}}#
{{item.user_info.title || '暫無簡介'}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
打賞
已打賞¥{{item.reward_price}}
{{item.like_count}}
{{item.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)

{{itemc.user_info.nickname}}

{{itemc.user_name}}

回復(fù) {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}
打賞
已打賞¥{{itemc.reward_price}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)
查看更多
打賞
已打賞¥{{reward_price}}
1239
{{like_count}}
{{collect_count}}
添加回復(fù) ({{post_count}})

相關(guān)推薦

快速安全登錄

使用微信掃碼登錄
{{item.label}} 加精
{{item.label}} {{item.label}} 板塊推薦 常見問題 產(chǎn)品動態(tài) 精選推薦 首頁頭條 首頁動態(tài) 首頁推薦
取 消 確 定
回復(fù)
回復(fù)
問題:
問題自動獲取的帖子內(nèi)容,不準確時需要手動修改. [獲取答案]
答案:
提交
bug 需求 取 消 確 定
打賞金額
當前余額:¥{{rewardUserInfo.reward_price}}
{{item.price}}元
請輸入 0.1-{{reward_max_price}} 范圍內(nèi)的數(shù)值
打賞成功
¥{{price}}
完成 確認打賞

微信登錄/注冊

切換手機號登錄

{{ bind_phone ? '綁定手機' : '手機登錄'}}

{{codeText}}
切換微信登錄/注冊
暫不綁定
CRMEB客服

CRMEB咨詢熱線 咨詢熱線

400-8888-794

微信掃碼咨詢

CRMEB開源商城下載 源碼下載 CRMEB幫助文檔 幫助文檔
返回頂部 返回頂部
CRMEB客服