1. 程式人生 > >介面開發-整合介面文件(swagger)

介面開發-整合介面文件(swagger)

在正式進入主題之前,先說說實際工作中遇到的問題。不算是傳統的原生APP開發,還是眼下的H5混合開發,只要是需要前後端通過介面配合的,往往都存在幾個普遍的問題

(1)介面文件誰來寫,尤其是跨部門,並且,前後端開發人員忙閒不一致時,很難安排;

(2)開發中,介面資料變動了,而介面文件更新不及時,後面專案交接時,那就會一塌糊塗(如果基於看程式碼的話,那就要看相關人員有沒有空了);

(3)用什麼寫也是個麻煩事,word?markdown?專門的介面系統?而且多人協作開發介面時,同步是個極其麻煩的事;

看過上面的問題,可見一個“規範的、可實時更新的”介面文件是多麼的重要。這一篇裡面,我們要說的就是把介面文件整合到工程裡面,讓寫介面的人員負責維護介面文件。好了,正式步入正題;

 

一、第三方選型

這裡不多說,我們選擇的就是swagger,其他類似的產品還有很多,自行百度。

 

二、新增依賴

<!-- swagger2 API介面文件,自動生成 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

  

三、swagger配置檔案

package com.univalsoft.springbootapimaster.common.configuration;

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

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.univalsoft.springbootapimaster.api.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("環球軟體 API 介面文件")
                .description("具體專案名稱,維護人")
//                .termsOfServiceUrl("http://www.by-health.com/")
                //.contact(contact)
                .version("1.0")
                .build();
    }

}

  

 

 四、給Controller添加註解

 

五、執行系統,瀏覽器中輸入 http://localhost:8080/swagger-ui.html

 

介面文件已經整合好了,後面更多的工作,需要介面開發人員認真負責,及時維護。這些與技術無關,看的更多的是一個人的耐心、責任心。

多說一句,“技術的高低只是暫時的,人品確是一輩子的”。