gradle + Springboot(web) + Swagger2 集成操作

1、问题描述

  随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、前后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。 前端和后端的唯一联系,变成了API接口;API文档变成了前后端开发人员联系的纽带,变得越来越重要。没有API文档工具之前,大家都是手写API文档的(维护起来相当困难),在什么地方书写的都有,有在confluence上写的,有在对应的项目目录下readme.md上写的,每个公司都有每个公司的玩法,无所谓好坏。但是能称之为“框架”的,估计也只有swagger了。

     首先对swagger做一个简介吧:是一款让你更好的书写API文档的框架; swagger是后台开发的神器,也是前后端交流的渠道。你可以用swagger做什么?首先,你以后基本可以告别单元测试了;其次,你不用再写接口文档了,也不需要写完之后再去对文档进行维护了;swagger可以完全模拟http请求,入参出参和实际情况差别几乎为零。

2、操作步骤

    2.1 配置:导入两个依赖包

implementation "io.springfox:springfox-swagger2:2.9.2"
implementation "io.springfox:springfox-swagger-ui:2.9.2"

    2.2 添加 swagger 配置类

package com.example.demo.config;

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;

@Configuration
@EnableSwagger2 //添加swagger启用注解
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))  // 注意修改此处的包名
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger2-集成系统") 
                .description("API接口文档")
                .version("1.1.0")
                .build();
    }
}

    2.3 在类、方法、参数上添加注解

package com.example.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(description = "测试类")
@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping("/get")
    @ApiOperation(value = "测试Swagger", notes = "测试Swagger2", httpMethod = "GET", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String")
    })
    public String sayHello(String name) throws Exception {
        return name + " hello Swagger!";
    }

}

    2.4 启动服务:浏览器输入http://ip:port/swagger-ui.html

http://localhost:8080/swagger-ui.html

    出现下面的画面就代表大功告成

    2.5 如何解决线上接口不被暴露?
     [1] 生产环境移除Swagger2
      * 使用注解 @Profile({"dev", "test"}) 表示在“开发”或“测试”环境开启,而在生产关闭

     [2] 使用springboot security过滤
      * 使用注解 @ConditionalOnProperty(name = "swagger2.enable", havingValue = "true")  
      * 然后在“开发”或“测试”配置中添加 swagger2.enable=true 即可开启,生产环境不配置则默认关闭Swagger.

     [3] 直接使用多环境配置,生产环境不启用Swagger2 (推荐使用)
      * application-xxx.yml文件

swagger2:
  enable: false/true

      * 调整 swagger 配置类

@Value("${swagger2.enable}")
private boolean swagger2Enable;

Docket(DocumentationType.SWAGGER_2).enable(swagger2Enable).build();

     [4] 三种配置方式源码,如下:

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
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;

@Configuration
@EnableSwagger2 //添加swagger启用注解
//@Profile({"dev", "test"}) //方式一
//@ConditionalOnProperty(name = "swagger2.enable", havingValue = "true") //方式二
public class Swagger2 {

    //读取yml文件配置
    @Value("${swagger2.enable}")
    private boolean swagger2Enable;

    /**
     * .enable()  控制是否进行初始化
     * .select()  初始化并返回一个API选择构造器
     * .paths(PathSelectors.any())   设置路径筛选器
     * .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.xxx"))  添加路径选择条件
     * .build();    构建
     *
     * PathSelectors 类的方法:
     *  - Predicate<String> any():满足条件的路径,该断言总为true
     *  - Predicate<String> none():不满足条件的路径,该断言总为false
     *  - Predicate<String> regex(final String pathRegex):符合正则的路径
     *
     * RequestHandlerSelectors 类的方法:
     *  - Predicate<RequestHandler> any():返回包含所有满足条件的请求处理器的断言,该断言总为true
     *  - Predicate<RequestHandler> none():返回不满足条件的请求处理器的断言,该断言总为false
     *  - Predicate<RequestHandler> basePackage(final String basePackage):返回一个断言(Predicate),该断言包含所有匹配basePackage下所有类的请求路径的请求处理器
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swagger2Enable)  //方式三
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))  // 注意修改此处的包名
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger2-集成系统")
                .description("API接口文档")
                .version("1.1.0")
                .build();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值