SpringBoot实战(八):集成Swagger

简介: SpringBoot实战(八):集成Swagger

强烈推荐一个大神的人工智能的教程:http://www.captainai.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


cd0636d9f9046288ceaa08f3b55b90f7_watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ=,size_16,color_FFFFFF,t_70.png


               2、Try it out


f80e5ff6ac088105753ce5cdd6281f68_watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ=,size_16,color_FFFFFF,t_70.png


               3、Execute


a17c0755f9c7009f3f2172173e279886_watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ=,size_16,color_FFFFFF,t_70.png


        三、项目地址及代码版本:


              1、地址:GitHub - dangnianchuntian/springboot: springboot


              2、代码版本:1.1.0-Release


【总结】


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


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


相关文章
|
1天前
|
前端开发 Java 应用服务中间件
从零手写实现 tomcat-08-tomcat 如何与 springboot 集成?
该文是一系列关于从零开始手写实现 Apache Tomcat 的教程概述。作者希望通过亲自动手实践理解 Tomcat 的核心机制。文章讨论了 Spring Boot 如何实现直接通过 `main` 方法启动,Spring 与 Tomcat 容器的集成方式,以及两者生命周期的同步原理。文中还提出了实现 Tomcat 的启发,强调在设计启动流程时确保资源的正确加载和初始化。最后提到了一个名为 mini-cat(嗅虎)的简易 Tomcat 实现项目,开源于 [GitHub](https://github.com/houbb/minicat)。
|
1天前
|
NoSQL Java MongoDB
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
【5月更文挑战第11天】本文介绍了如何将非关系型数据库MongoDB与Spring Boot框架集成,以实现高效灵活的数据管理。Spring Boot简化了Spring应用的构建和部署,MongoDB则以其对灵活数据结构的处理能力受到青睐。集成步骤包括:添加MongoDB依赖、配置连接信息、创建数据访问对象(DAO)以及进行数据操作。通过这种方式,开发者可以充分利用两者优势,应对各种数据需求。在实际应用中,结合微服务架构等技术,可以构建高性能、可扩展的系统。掌握MongoDB与Spring Boot集成对于提升开发效率和项目质量至关重要,未来有望在更多领域得到广泛应用。
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
|
1天前
|
消息中间件 JSON Java
RabbitMQ的springboot项目集成使用-01
RabbitMQ的springboot项目集成使用-01
|
1天前
|
搜索推荐 Java 数据库
springboot集成ElasticSearch的具体操作(系统全文检索)
springboot集成ElasticSearch的具体操作(系统全文检索)
|
1天前
|
消息中间件 Java Spring
Springboot 集成Rabbitmq之延时队列
Springboot 集成Rabbitmq之延时队列
6 0
|
1天前
|
网络协议 Java Spring
Springboot 集成websocket
Springboot 集成websocket
11 0
|
1天前
|
XML Java 数据库
springboot集成flowable
springboot集成flowable
|
1天前
|
安全 Java 数据库连接
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通
|
1天前
|
缓存 NoSQL Java
springboot业务开发--springboot集成redis解决缓存雪崩穿透问题
该文介绍了缓存使用中可能出现的三个问题及解决方案:缓存穿透、缓存击穿和缓存雪崩。为防止缓存穿透,可校验请求数据并缓存空值;缓存击穿可采用限流、热点数据预加载或加锁策略;缓存雪崩则需避免同一时间大量缓存失效,可设置随机过期时间。文章还提及了Spring Boot中Redis缓存的配置,包括缓存null值、使用前缀和自定义过期时间,并提供了改造代码以实现缓存到期时间的个性化设置。
http://www.vxiaotou.com