1. 程式人生 > >SpringBoot(二十)Swagger2-自動生成RESTful規範API文件

SpringBoot(二十)Swagger2-自動生成RESTful規範API文件

 

Swagger2 方式,一定會讓你有不一樣的開發體驗:功能豐富 :支援多種註解,自動生成介面文件介面,支援在介面測試API介面功能;及時更新 :開發過程中花一點寫註釋的時間,就可以及時的更新API文件,省心省力;整合簡單 :通過新增pom依賴和簡單配置,內嵌於應用中就可同時釋出API介面文件介面,不需要部署獨立服務。

v新增pom依賴

        <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>

v配置swagger-ui

spring-boot有自己的一套web端攔截機制,若需要看到swagger釋出的api文件介面,需要做一些特殊的配置,將springfox-swagger-ui包中的ui介面暴露給spring-boot資源環境。

package com.demo.filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.annotation.Resource; /** * Created by toutou on 2018/12/30. */ @Configuration public class WebConfig implements WebMvcConfigurer { @Resource private MyTestInterceptor myTestInterceptor; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/"); registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }

v配置API文件

spring-boot 和 swagger 整合時,可以通過註解注入相關配置。通過這些配置可以指定在spring-boot啟動時掃描哪些controller層的資料夾,另外可以指定API文件頁的標題和描述資訊等內容。

package com.demo.common;

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;

/**
 * Created by toutou on 2018/12/30.
 */
@Configuration
@EnableSwagger2
public class Swagger2 {


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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("測試專案 RESTful APIs")
                .description("測試專案後臺api介面文件")
                .version("1.0.0")
                .build();
    }

}

注意把com.demo.controller更換成Controller的包名

vAPI文件編寫示例

我們一般在Controller層,將詳盡的API介面輸入輸出在程式碼中通過註解進行相關描述,下面給出一個介面描寫示例,具體的寫法可以參考其api文件的例項:

package com.demo.controller;

import com.demo.pojo.UserDetails;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by toutou on 2018/12/30.
 */
@Api(value = "PageController", description = "使用者登入登出介面")
@Controller
@RequestMapping("/")
public class PageController {

    @ApiOperation(value="使用者登入", notes="使用者登入介面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "使用者名稱", required = true ,dataType = "string"),
            @ApiImplicitParam(name = "passwd", value = "密碼", required = true ,dataType = "string")
    })
    @RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ModelMap login(UserDetails data, HttpServletRequest request){
        // todo 實現
        return null;
    }

}

v效果

 完成API文件的編寫工作之後,正常啟動spring-boot,假如後臺埠為8080,那麼訪問http://localhost:8081/swagger-ui.html,可以訪問到如下介面:

通過該介面,不僅可以看到自動生成的所有API文件資訊,還可以對任意介面進行線上測試,非常方便,彷彿可以解除安裝Postman似的。〔^.べ〕:

 


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關於作者:專注於基礎平臺的專案開發。如有問題或建議,請多多賜教!
版權宣告:本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連結。
特此宣告:所有評論和私信都會在第一時間回覆。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信
聲援博主:如果您覺得文章對您有幫助,可以點選文章右下角推薦一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!