栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot - SWAGGER2公共模块的抽象集成与使用(二)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot - SWAGGER2公共模块的抽象集成与使用(二)

写在前面

前后端分离的项目中,使用 Swagger2 来构建在线接口文档是必不可少的,如果所有的微服务都配置SWAGGER2的信息太麻烦了,所以接下来一步一步的带着大家构建统一的SWAGGER组件。

在阅读该博文前需要先了解以下内容:
JAVA8 - java.util.function.Predicate
SpringBoot - spring.factories的作用是什么?
SpringBoot - Swagger2的集成与使用(一)

如何创建 1. 创建一个单独的模块(servicex-common-swagger) 2. 在该模块中引入依赖


    org.springframework.boot
    spring-boot-starter-web




    io.springfox
    springfox-swagger2




    io.springfox
    springfox-swagger-ui




    org.projectlombok
    lombok
    provided



    org.springframework.boot
    spring-boot-configuration-processor
    true

3. 自定义SWAGGER2注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({SwaggerAutoConfiguration.class})
public @interface EnableServiceSwagger2 {
}
4. 创建自动装配SWAGGER2的对象
@Configuration
@EnableSwagger2
@EnableAutoConfiguration
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
public class SwaggerAutoConfiguration {

    // 默认的排除路径, 排除SPRING BOOT默认的错误处理路径和端点
    private static final List DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/**");

    private static final String BASE_PATH = "/**";

    @Bean
    @ConditionalOnMissingBean
    public SwaggerProperties swaggerProperties() {
        return new SwaggerProperties();
    }

    @Bean
    public Docket api(SwaggerProperties swaggerProperties) {
        // base-path处理
        if (swaggerProperties.getBasePath().isEmpty()) {
            swaggerProperties.getBasePath().add(BASE_PATH);
        }
        // SWAGGER会解析的URL规则的处理, 将配置的需要解析的URL规则放进LIST中
        List> basePath = new ArrayList>();
        swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path)));

        // 在BASE-PAHT基础上需要排除的URL规则的处理, 将配置的需要排除的URL规则放进LIST中
        if (swaggerProperties.getExcludePath().isEmpty()) {
            swaggerProperties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH);
        }
        List> excludePath = new ArrayList<>();
        swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
        return new Docket(DocumentationType.SWAGGER_2)
                .host(swaggerProperties.getHost())
                // 在API-INFO中构建文档的基本信息. 例如描述、联系人信息、版本、标题等
                .apiInfo(apiInfo(swaggerProperties)).select()
                // 通过APIS方法配置要扫描的CONTROLLER的位置(会解析的包路径)
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))

                // [GUVA]通过PATHS方法配置路径(会解析的URL规则, 需要在BASE-PAHT的基础上排除不需要解析的URL规则)
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))

                .build()
                .pathMapping("/");

    }
    // 文档基本信息
    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .license(swaggerProperties.getLicense())
                .licenseUrl(swaggerProperties.getLicenseUrl())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
                .version(swaggerProperties.getVersion())
                .build();
    }
}
5. 创建SWAGGER2配置对象
@Data
@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties {

    // 是否开启SWAGGER2
    private Boolean enabled;

    // SWAGGER会解析的包路径
    private String basePackage = "";

    // SWAGGER会解析的URL规则
    private List basePath = new ArrayList<>();

    // 在BASE-PAHT基础上需要排除的URL规则
    private List excludePath = new ArrayList<>();

    // 文档标题(如: 广告服务接口文档)
    private String title = "";

    // 文档描述(如: 该文档用于描述广告服务提供的接口)
    private String description = "";

    // 文档的版本
    private String version = "1.0";

    // 许可证
    private String license = "Powered By hadoopx";

    // 许可证URL
    private String licenseUrl = "http://hadoopx.cn";

    // 服务条款URL
    private String termsOfServiceUrl = "";

    // HOST信息
    private String host = "";

    // 联系人信息
    private Contact contact = new Contact();

    // 全局统一鉴权配置
    private Authorization authorization = new Authorization();

    @Data
    public static class Contact {
        // 联系人
        private String name = "ROCKY";
        // 联系人URL
        private String url = "";
        // 联系人邮箱
        private String email = "";
    }
    @Data
    public static class Authorization {
        // 鉴权策略ID,需要和SecurityReferences ID保持一致
        private String name = "";

        // 需要开启鉴权URL的正则
        private String authRegex = "^.*$";

        // 鉴权作用域列表
        private List authorizationScopeList = new ArrayList<>();

        private List tokenUrlList = new ArrayList<>();
    }
    @Data
    public static class AuthorizationScope {
        // 作用域名称
        private String scope = "";
        // 作用域描述
        private String description = "";
    }
}
6. 配置场景启动器的加载策略
// 在resources/META-INF/spring.factories的文件中添加如下配置:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
  com.hadoopx.common.swagger.config.SwaggerAutoConfiguration
7. 编译打包… 如何使用
1. 引入依赖, 在微服务的POM.XML中添加如下依赖

   
   
       com.hadoopx
       servicex-common-swagger
       ${servicex.version}
   

2. 添加注解, 在微服务的启动类中添加如下依赖
   @EnableServiceSwagger2

3. 在线API文档
   http://微服务的IP或者LOCALHOST:微服务的端口号/swagger-ui.html
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000042.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号