SpringBoot實戰(八):集成Swagger

強烈推薦一個大神的人工智能的教程:http://www.captainbed.net/zhanghan

【前言】

       前後端分離是現在系統的主流,前端人員更多專注於前端功能,後端人員更加關注後端極大提高開發效率;一般情況下前後端由不同的開發團隊進行開發;所以免不了要有一份接口文檔,手寫接口文檔,維護接口文檔團隊間溝通,調試等也是需要花費一定的時間,Swagger就在一定程度上解決了以上問題;今天將自己的項目集成Swagger;

【集成Swagger之路】

         一、Springboot集成Swagger的方式

                1、Pom中增加相關依賴

        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-swagger2.version}</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-swagger-ui.version}</version>
        </dependency>

                2、增加Swagger配置類

package com.zhanghan.zhboot.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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;

/**
 * Swagger2配置類
 * 在與spring boot集成時,放在與Application.java同級的目錄下。
 * 通過@Configuration註解,讓Spring來加載該類配置。
 * 再通過@EnableSwagger2註解來啓用Swagger2。
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class SwaggerConfig {

    //定義掃描的controller的路徑
    private final static String controllerPath = "com.zhanghan.zhboot.controller";

    /**
     * 創建API應用
     * apiInfo() 增加API相關信息
     * 通過select()函數返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展現,
     * 本例採用指定掃描的包路徑來定義指定要建立API的目錄。
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(controllerPath))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 創建該API的基本信息(這些基本信息會展現在文檔頁面中)
     * 訪問地址:http://項目實際地址/swagger-ui.html
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot集成swagger")
                .description("簡單優雅的restfun風格,https://blog.csdn.net/zhanghan18333611647")
                .termsOfServiceUrl("https://blog.csdn.net/zhanghan18333611647")
                .version("1.0")
                .build();
    }

}

                3、application中增加Swagger開關(此開關爲true則代表啓用Swagger;false則不啓用Swagger;一般爲安全起見生產環境置爲false)

#****************************swagger***************************
#true is display swagger; false not disply swagger
swagger.enable=true

                4、controller中增加相關的Swagger描述

package com.zhanghan.zhboot.controller;

import com.mysql.jdbc.StringUtils;
import com.zhanghan.zhboot.controller.request.MobileCheckRequest;
import com.zhanghan.zhboot.properties.MobilePreFixProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Api(value = "校驗手機號控制器",tags = {"校驗手機號控制器"})
public class CheckMobileController {

    @Autowired
    private MobilePreFixProperties mobilePreFixProperties;

    @ApiOperation(value="優雅校驗手機號格式方式",tags = {"校驗手機號控制器"})
    @RequestMapping(value = "/good/check/mobile", method = RequestMethod.POST)
    public Map goodCheckMobile(@RequestBody @Validated MobileCheckRequest mobileCheckRequest) {

        String countryCode = mobileCheckRequest.getCountryCode();
        String proFix = mobilePreFixProperties.getPrefixs().get(countryCode);

        if (StringUtils.isNullOrEmpty(proFix)) {
            return buildFailResponse();
        }

        String mobile = mobileCheckRequest.getMobile();

        Boolean isLegal = false;
        if (mobile.startsWith(proFix)) {
            isLegal = true;
        }


        Map map = new HashMap();
        map.put("code", 0);
        map.put("mobile", mobile);
        map.put("isLegal", isLegal);
        map.put("proFix", proFix);
        return map;
    }

    @ApiOperation(value="擴展性差校驗手機號格式方式",tags = {"校驗手機號控制器"})
    @RequestMapping(value = "/bad/check/mobile", method = RequestMethod.POST)
    public Map badCheckMobile(@RequestBody MobileCheckRequest mobileCheckRequest) {

        String countryCode = mobileCheckRequest.getCountryCode();

        String proFix;
        if (countryCode.equals("CN")) {
            proFix = "86";
        } else if (countryCode.equals("US")) {
            proFix = "1";
        } else {
            return buildFailResponse();
        }

        String mobile = mobileCheckRequest.getMobile();

        Boolean isLegal = false;
        if (mobile.startsWith(proFix)) {
            isLegal = true;
        }


        Map map = new HashMap();
        map.put("code", 0);
        map.put("mobile", mobile);
        map.put("isLegal", isLegal);
        map.put("proFix", proFix);
        return map;
    }

    private Map buildFailResponse() {
        Map map = new HashMap();
        map.put("code", 1);
        map.put("mobile", "");
        map.put("isLegal", false);
        map.put("proFix", "");
        return map;
    }


}

                5、請求實體中增加相關的Swagger描述

package com.zhanghan.zhboot.controller.request;


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;

@ApiModel("手機號校驗請求實體")
@Data
public class MobileCheckRequest {

    @ApiModelProperty(value = "國家編碼",required = true)
    @NotNull
    private String countryCode;

    @ApiModelProperty(value = "手機號",required = true)
    @NotNull
    private String mobile;


}

         二、效果展示

                1、啓動項目訪問地址:http://localhost:8080/swagger-ui.html

                2、Try it out

                3、Execute

         三、項目地址及代碼版本:

               1、地址:https://github.com/dangnianchuntian/springboot

               2、代碼版本:1.1.0-Release

【總結】

         1、充分利用好工具提高效率;

         2、小工具有大用處,多去研究。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章