SpringBoot和Swagger結合提高API開發效率

來源:互聯網
上載者:User

現在Web開發越來越傾向於前後端分離,前端使用AngularJS,React,Vue等,部署在NodeJS上,後面採用SpringBoot發布Rest服務,前後端進行分離。這樣的架構靈活且特別適合大型團隊的協作開發。 那麼問題來了,因為前端都是和後端通過API進行互動的,那麼前後端的Rest API的介面如何進行定義和溝通呢。首先想到的應該就是Swagger。

那麼什麼是Swagger,Swagger的目標是為REST APIs 定義一個標準的,與語言無關的介面,使人和電腦在看不到源碼或者看不到文檔或者不能通過網路流量檢測的情況下能發現和理解各種服務的功能。當服務通過Swagger定義,消費者就能與遠端服務互動通過少量的實現邏輯。類似於低級編程介面,Swagger去掉了調用服務時的很多猜測。 瀏覽 Swagger-Spec 去瞭解更多關於Swagger 項目的資訊,包括附加的支援其他語言的庫。

那麼在SpringBoot中,如何和Swagger進行整合呢。其實非常的簡單,只需要把
下面的依賴添加到Maven項目的pom.xml檔案中,然後加上一個配置java類就可以了。SpringBoot就會自動應用Swagger,並產生相應的介面。
@Maven依賴

        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger2</artifactId>            <version>2.6.1</version>            <scope>compile</scope>        </dependency>        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger-ui</artifactId>            <version>2.6.1</version>            <scope>compile</scope>        </dependency>

@加一個Swagger的配置類,從而控制要暴露哪些package下面的REST API已經Swagger web頁面上需要顯示的應用相關的介紹資訊。

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;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;@Configuration@EnableSwagger2public class SwaggerConfig {    @Bean    public Docket createRestApi() {        return new Docket(DocumentationType.SWAGGER_2)                .apiInfo(apiInfo())                .select()                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))                .paths(PathSelectors.any())                .build();    }    private ApiInfo apiInfo() {        ApiInfo apiInfo = new ApiInfo(                "Example REST API",                "Example REST API for Service Pack",                "1.0",                "Terms of service",                new Contact("Chancein007 Team", "", ""),"","");        return apiInfo;    }}

上面的2個步驟完成後,就直接啟動SpringBoot,當SpringBoot啟動完成後,直接在網站後面加上swagger-ui.html就能訪問,具體見下圖,也太神奇了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.