接口開發-集成接口文檔(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

 

接口文檔已經集成好了,后面更多的工作,需要接口開發人員認真負責,及時維護。這些與技術無關,看的更多的是一個人的耐心、責任心。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM