1. 程式人生 > >如何在spring-boot web專案中啟用swagger

如何在spring-boot web專案中啟用swagger

swagger的三個專案及其作用

我們開啟swagger的官網,會發現有三個swagger相關的專案,它們分別是

  1. swagger-editor 作用是通過寫程式碼,生成文件描述(一個json檔案或其他格式的api元資料檔案)
  2. swagger-ui 通過請求文件描述(一個json檔案)的資料,把api的文件顯示在頁面上
  3. swagger-codegenerator 通過文件描述,來生成實現的程式碼

如何在spring-boot專案中整合swagger?

我們使用springfox-swagger這個專案來把swagger的功能整合到我們的專案中來,springfox-swagger會自動掃描定義在Controller上的API的相關的註解,生成api的元資料json檔案,然後提供的一個swagger的頁面,當我們訪問這個頁面的時候,前端的js會去請求這個API的元資料檔案,把API的相關資訊展示出來,方便我們閱讀和線上除錯

整合到spring-boot web專案的步驟:

1.在專案的依賴一遍加入springfox-swagger的相關的依賴

由於我用的構建工具是gradle,所以就用下邊的方式來引入依賴,

compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'

2.定義swagger的配置類,引入啟用swaggger

在spring-boot專案可以自動掃描到的包下邊,配置以下的配置類:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created with Intellij IDEA
 *
 * @author: jiaoyiping
 * Mail: 
[email protected]
* Date: 2018/11/22 * Time: 15:38 * To change this template use File | Settings | Editor | File and Code Templates */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket customDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { Contact contact = new Contact("焦一平", "http://www.cnblogs.com/jiaoyiping/", "[email protected]"); return new ApiInfoBuilder() .title("元資料管理API介面") .description("工具鏈元資料管理") .contact(contact) .version("1.1.0") .build(); } }

3.在Controller裡邊定義API的相關的註解

以下是一個API註解的例子:

@RequestMapping(value = "/checkprojectcode/{projectcode}", method = RequestMethod.GET)
    @ApiOperation(value = "檢查專案編號是否已經存在")
    public ResponseEntity<String> checkProjectCodeExists(@PathVariable("projectcode") String projectCode) {
        ResponseEntity<String> result;
        if (projectService.isProjectCodeExist(projectCode)) {
            result = ResponseEntity.ok("專案編號已存在");
        } else {
            result = ResponseEntity.ok("專案編號不存在");
        }
        return result;
    }

@ApiOperation註解提供了api的名稱和描述資訊

最終效果

啟動專案,訪問專案路徑下的 v2/api-docs 這個地址,可以看到生成的json資料

訪問專案路徑下的 swagger-ui.html路徑,可以檢視和除錯我們寫的api的資訊,所以的被@Controller註解的類都會顯示在和這個頁面上,添加了額外的api主機的介面,會有額外的描述資訊