SpringBoot实战(八):集成Swagger

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/u012829124/article/details/91900759

强烈推荐一个大神的人工智能的教程: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、小工具有大用处,多去研究。

猜你喜欢

转载自blog.csdn.net/u012829124/article/details/91900759