springboot快速集成Swagger2集成公共服务,支持开关和子项目包路径配置


团队开发痛点:

  • API 接口众多,细节复杂,需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等,想要高质量的完成这份文档需要耗费大量的精力;

  • 难以维护。随着需求的变更和项目的优化、推进,接口的细节在不断地演变,接口描述文档也需要同步修订,可是文档和代码处于两个不同的媒介,除非有严格的管理机制,否则很容易出现文档、接口不一致的情况

Swagger2 的出现就是为了从根本上解决上述问题。它作为一个规范和完整的框架,可以用于生成、描述、调用和可视化 RESTful 风格的 Web 服务:

  1. 接口文档在线自动生成,文档随接口变动实时更新,节省维护成本

  2. 支持在线接口测试,不依赖第三方工具

注意点: Swagger2是支持在线接口测试的,所以对于生产环境,准生产环境,必须屏蔽该入口,防止因为Swagger2的在线接口测试导致生产问题或者数据污染。**

第一步集成pom

<!-- swagger -->  
<dependency>  
    <groupId>io.springfox</groupId>  
    <artifactId>springfox-swagger-ui</artifactId>  
    <version>2.4.0</version>  
</dependency>  
<dependency>  
    <groupId>io.springfox</groupId>  
    <artifactId>springfox-swagger2</artifactId>  
    <version>2.4.0</version>  
</dependency>

**第二步: Swagger2 的配置**

package com.common.base.config;

import com.common.base.utils.StringUtil;
import com.common.base.utils.YamlUtil;
import org.springframework.beans.factory.annotation.Autowired;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Auther: tony_t_peng
 * @Date: 2020-08-14 15:42
 * @Description: 
 */
@Configuration
//是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable",  havingValue = "true")
@EnableSwagger2
public class Swagger2Config {

    @Autowired
    private ProfileConfig profileConfig;

    private static final String SWAGGER_BASE_PACKAGE="swagger.base.package";



    // swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        String active = profileConfig.getActiveProfile();//读取当前的环境active 
        String swaggerBasePackage = YamlUtil.getApplicationVal(SWAGGER_BASE_PACKAGE,active);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 为当前包路径
                .apis(RequestHandlerSelectors.basePackage(swaggerBasePackage)).paths(PathSelectors.any())
                .build();
    }
    // 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 页面标题
                .title("Swagger2 构建RESTful API")
                // 创建人信息
                .contact(new Contact("TONY_T_PENG",  "",  ""))
                // 版本号
                .version("1.0")
                // 描述
                .description("API 描述")
                .build();
    }
}



/**
 * @Auther: tony_t_peng
 * @Date: 2020-08-07 15:35
 * @Description: 获取profile.active提供方法,此方法可以在sping容器完成创建之前,
 * 获取环境参数
 */
@Configuration
@AutoConfigureOrder(0) 
public class ProfileConfig {


    @Autowired
    private ApplicationContext context;

    public String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }

}

这两步可以集成到公共服务中,子项目pom去依赖公共服务,减少重复造轮子。

第三步: 配置api

@RestController
@RequestMapping("/question")
@Api("questionController相关的api")
public class QuestionController {

    public static Logger logger = LoggerFactory.getLogger(QuestionController.class);

    @Autowired
    private UwConvertQuestionService convertQuestionService;

    @RequestMapping(value = "/test",method = RequestMethod.POST)
    @ApiOperation(value = "测试",tags={"测试标题"}, notes = "标题内容",httpMethod = "POST")
    public Result<ConvertQuestionResponseMO> test(@RequestBody @Valid ConvertQuestionRequestMO request)
    {

        return null;
    }


}

注:如果想要屏蔽某些接口:使用注解 @ApiIgnore

第四步:配置扫包路径和swagger启动开关,swagger功能开启

服务配置扫包路径:application-dev.yml

swagger:
  enable: true
  base:
    package: com.XXX.controller

第五步 启动springboot服务,访问http://localhost:9090/swagger- ui.html


原文链接:https://www.cnblogs.com/ptcnblog/p/13516434.html