溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Springboot中如何集成Swagger2框架

發(fā)布時(shí)間:2021-07-08 10:20:51 來源:億速云 閱讀:150 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)Springboot中如何集成Swagger2框架的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

摘要:在項(xiàng)目開發(fā)中,往往期望做到前后端分離,也就是后端開發(fā)人員往往需要輸出大量的服務(wù)接口,接口的提供方無論是是Java還是PHP等語言,往往會(huì)要花費(fèi)一定的精力去寫接口文檔,比如A接口的地址、需要傳遞參數(shù)情況、返回值的JSON數(shù)據(jù)格式以及每一個(gè)字段說明、當(dāng)然還要考慮HTTP請(qǐng)求頭、請(qǐng)求內(nèi)容等信息。隨著項(xiàng)目的進(jìn)度快速高速的迭代,后端輸出的接口往往會(huì)面臨修改、修復(fù)等問題,那也意味著接口文檔也要進(jìn)行相應(yīng)的調(diào)整。接口文檔的維護(hù)度以及可讀性就大大下降。

既然接口文檔需要花費(fèi)精力去維護(hù),還要適當(dāng)?shù)倪M(jìn)行面對(duì)面交流溝通,我們何不想一個(gè)辦法,第一:可以不用寫接口文檔;第二:前端與后端溝通接口問題的時(shí)候,后端是否可以提供一個(gè)URL,在這個(gè)URL中羅列出所有可以調(diào)用的服務(wù)接口,并在每個(gè)服務(wù)接口中羅列出參數(shù)的說明,返回值的說明,第三:后端接口如果能模擬調(diào)用就所有問題都解決了。本文我們重點(diǎn)講解一下Sringboot中集成Swagger2框架。

1.1. 添加Swagger2依賴

在項(xiàng)目的pom.xml文件中增加如下的依賴。

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

首先,我們需要建立一個(gè)啟動(dòng)類,代碼如下:

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

然后在上述類的同級(jí)目錄中新建swagger2的配置類如下所示:

@Configuration
@EnableSwagger2
public class Swagger2 {
  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.shareniu.web"))
        .paths(PathSelectors.any())
        .build();
  }
  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("跟著分享牛學(xué)習(xí)Springboot源碼分析系列課程")
        .description("更多Spring Boot相關(guān)文章請(qǐng)關(guān)注分享牛的博客")
        .termsOfServiceUrl("http://www.shareniu.com/")
        .contact("牛牛")
        .license("Copyright 2017-2018 分享牛")
        .version("1.0")
        .build();
  }
}

@Configuration制定了spring要加載這個(gè)類,@EnableSwagger2注解要開啟Swagger功能。

上述中的ApiInfo最終都會(huì)展現(xiàn)在前端,我們使用了掃描包的方式配置配置,也就是RequestHandlerSelectors.basePackage。在這個(gè)包以及子包中的控制器最終都是生成API文檔。(除了被@ApiIgnore注解指定的請(qǐng)求)。

1.2. 新增文檔說明

上述的類聲明之后,我們其實(shí)就可以直接調(diào)用了,但是為了增加文檔的可讀性,我們還是需要在接口中增加一些說明,我們先寫一個(gè)控制器如下所示:

@RestController
@RequestMapping(value="/users")
public class UserController {
  static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
  static {
   User user = new User();
   user.setAge(18);
   user.setId(1L);
   user.setName("aa");
   users.put(1L, user);
  }
  @ApiOperation(value="獲取所有用戶列表", notes="")
  @RequestMapping(value={""}, method=RequestMethod.GET)
  public List<User> getUserList() {
    List<User> r = new ArrayList<User>(users.values());
    return r;
  }
  @ApiOperation(value="創(chuàng)建新的用戶", notes="根據(jù)User對(duì)象創(chuàng)建用戶")
  @ApiImplicitParam(name = "user", value = "用戶詳細(xì)實(shí)體user", required = true, dataType = "User")
  @RequestMapping(value="", method=RequestMethod.POST)
  public String postUser(@RequestBody User user) {
    users.put(user.getId(), user);
    return "success";
  }
  @ApiOperation(value="獲取用戶詳細(xì)信息", notes="根據(jù)url的id來獲取用戶詳細(xì)信息")
  @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
  @RequestMapping(value="/{id}", method=RequestMethod.GET)
  public User getUser(@PathVariable Long id) {
    return users.get(id);
  }
  @ApiOperation(value="更新用戶詳細(xì)信息", notes="根據(jù)url的id來指定更新對(duì)象")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"),
      @ApiImplicitParam(name = "user", value = "用戶詳細(xì)實(shí)體user", required = true, dataType = "User")
  })
  @RequestMapping(value="/{id}", method=RequestMethod.PUT)
  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";
  }
  @ApiOperation(value="刪除已存在的用戶", notes="根據(jù)url的id來指定刪除對(duì)象")
  @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
  @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
  public String deleteUser(@PathVariable Long id) {
    users.remove(id);
    return "success";
  }
}

 @ApiOperation:用來描述該接口的作用??梢酝ㄟ^該注解說明接口的職責(zé)、返回頭信息、方法的請(qǐng)求方式("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH")、協(xié)議( http, https, ws, wss)、http狀態(tài)碼。
@ApiImplicitParam:用來給參數(shù)增加說明??梢栽O(shè)置參數(shù)的名稱、是否是必填項(xiàng)、參數(shù)的描述信息、是否只讀等。

上述代碼提交之后,啟動(dòng)springboot,訪問http://127.0.0.1:8080/swagger-ui.html,如下圖所示: 

Springboot中如何集成Swagger2框架

上圖分為兩個(gè)部分,上部分是通過Swagger2類配置出來的,下半部分是UserController類中的接口文檔。
這里我們以/user為例進(jìn)行說明:

點(diǎn)擊/user如下圖所示: 

Springboot中如何集成Swagger2框架

上圖黃色的地方表示,該接口返回的樣例數(shù)據(jù)。也就是User的數(shù)據(jù)結(jié)構(gòu)。Response Content Type:接口返回的頭信息。點(diǎn)擊Try it out。如下所示: 

Springboot中如何集成Swagger2框架

該接口返回的baody、code碼、響應(yīng)頭已經(jīng)成功返回了。

感謝各位的閱讀!關(guān)于“Springboot中如何集成Swagger2框架”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI