• 【创建公共的swagger3组件】Spring Cloud 14


    背景

    在开发微服务的时候,一个项目的文件中会有多个接口模块,每个模块中有多个接口,若在每个模块中配置swagger的话,每创建一个新模块就要重新配置一次swagger,这样就会造成工作的重复。

    参考RuoYi源码中swagger内容总结的学习笔记,RuoYi官网入口

    目标

    将swagger独立出来做成公共的组件,只要在每个接口的启动类中加入自定义的swagger启用注解即可使用。

    项目目录结构

    如下图:
    在这里插入图片描述

    项目中pom.xml的依赖关系

    commom-swagger

    pom.xml

    <dependencies>
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-boot-starterartifactId>
                <version>${springfox.version}version>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-autoconfigureartifactId>
                <version>${spring-boot-autoconfigure.version}version>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-validationartifactId>
                <version>${spring-boot-starter-validation.version}version>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
                <version>${spring-boot-starter-web.version}version>
            dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    抽离swagger公共部分

    自定义swagger配置

    zhang-commom-swagger子模块中,创建自定义包名,此处我创建的为zhang.commom.swagger3,并在此包下创建两个文件夹,分别为annotationconfig。用于存放自定义注解和swagger的配置。

    在 config中创建配置
    创建swagger的配置

    创建文件名为SwaggerProperties.java 的类文件,此文件中的属性就是配置在yml文件中的配置。内容如下:

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Component
    @ConfigurationProperties("swagger")
    public class SwaggerProperties
    {
        /**
         * 是否开启swagger
         */
        private Boolean enabled;
    
        /**
         * 组名
         */
        private String groupName;
    
        /**
         * swagger会解析的包路径
         **/
        private String basePackage = "";
    
        /**
         * swagger会解析的url规则
         **/
        private List<String> basePath = new ArrayList<>();
    
        /**
         * 在basePath基础上需要排除的url规则
         **/
        private List<String> excludePath = new ArrayList<>();
    
        /**
         * 标题
         **/
        private String title = "";
    
        /**
         * 描述
         **/
        private String description = "";
    
        /**
         * 版本
         **/
        private String version = "";
    
        /**
         * 许可证
         **/
        private String license = "";
    
        /**
         * 许可证URL
         **/
        private String licenseUrl = "";
    
        /**
         * 服务条款URL
         **/
        private String termsOfServiceUrl = "";
    
        /**
         * host信息
         **/
        private String host = "";
    
        /**
         * 联系人信息
         */
        private Contact contact = new Contact();
        
        public String getGroupName() {
            return groupName;
        }
    
        public void setGroupName(String groupName) {
            this.groupName = groupName;
        }
       
        public Boolean getEnabled()
        {
            return enabled;
        }
    
        public void setEnabled(Boolean enabled)
        {
            this.enabled = enabled;
        }
    
        public String getBasePackage()
        {
            return basePackage;
        }
    
        public void setBasePackage(String basePackage)
        {
            this.basePackage = basePackage;
        }
    
        public List<String> getBasePath()
        {
            return basePath;
        }
    
        public void setBasePath(List<String> basePath)
        {
            this.basePath = basePath;
        }
    
        public List<String> getExcludePath()
        {
            return excludePath;
        }
    
        public void setExcludePath(List<String> excludePath)
        {
            this.excludePath = excludePath;
        }
    
        public String getTitle()
        {
            return title;
        }
    
        public void setTitle(String title)
        {
            this.title = title;
        }
    
        public String getDescription()
        {
            return description;
        }
    
        public void setDescription(String description)
        {
            this.description = description;
        }
    
        public String getVersion()
        {
            return version;
        }
    
        public void setVersion(String version)
        {
            this.version = version;
        }
    
        public String getLicense()
        {
            return license;
        }
    
        public void setLicense(String license)
        {
            this.license = license;
        }
    
        public String getLicenseUrl()
        {
            return licenseUrl;
        }
    
        public void setLicenseUrl(String licenseUrl)
        {
            this.licenseUrl = licenseUrl;
        }
    
        public String getTermsOfServiceUrl()
        {
            return termsOfServiceUrl;
        }
    
        public void setTermsOfServiceUrl(String termsOfServiceUrl)
        {
            this.termsOfServiceUrl = termsOfServiceUrl;
        }
    
        public String getHost()
        {
            return host;
        }
    
        public void setHost(String host)
        {
            this.host = host;
        }
    
        public Contact getContact()
        {
            return contact;
        }
    
        public void setContact(Contact contact)
        {
            this.contact = contact;
        }
    
        public static class Contact
        {
            /**
             * 联系人
             **/
            private String name = "";
            /**
             * 联系人url
             **/
            private String url = "";
            /**
             * 联系人email
             **/
            private String email = "";
    
            public String getName()
            {
                return name;
            }
    
            public void setName(String name)
            {
                this.name = name;
            }
    
            public String getUrl()
            {
                return url;
            }
    
            public void setUrl(String url)
            {
                this.url = url;
            }
    
            public String getEmail()
            {
                return email;
            }
    
            public void setEmail(String email)
            {
                this.email = email;
            }
        }
        
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    创建swagger 资源映射路径配置

    创建文件名为SwaggerWebConfiguration.java 的类文件,实现WebMvcConfigurer接口,重写addResourceHandlers方法

    @Configuration
    public class SwaggerWebConfiguration implements WebMvcConfigurer
    {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry)
        {
            /** swagger-ui 地址 */
            registry.addResourceHandler("/swagger-ui/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    创建 swagger 在 springboot 2.6.x 不兼容问题的处理配置

    创建文件名为SwaggerBeanPostProcessor.java 的类文件,实现BeanPostProcessor接口,重写postProcessAfterInitialization方法

    @Component
    public class SwaggerBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
            }
            return bean;
        }
    
        private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
            List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
                    .collect(Collectors.toList());
            mappings.clear();
            mappings.addAll(copy);
        }
    
        @SuppressWarnings("unchecked")
        private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
            try {
                Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                field.setAccessible(true);
                return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    开始进行swagger的配置

    创建SwaggerAutoConfiguration.java文件

    
    @Configuration
    @EnableOpenApi
    @EnableAutoConfiguration
    @ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = false) // 启动配置,默认启关闭,生产环境建议将改为swagger.enabled=false
    public class SwaggerAutoConfiguration {
        /**
         * 默认的排除路径,排除Spring Boot默认的错误处理路径和端点
         */
        private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/**");
    
        private static final String BASE_PATH = "/**";
    
        @Bean
        @ConditionalOnMissingBean // 保证SwaggerProperties对象单例
        public SwaggerProperties swaggerProperties() {
            return new SwaggerProperties();
        }
    
        @Bean
        public Docket api(SwaggerProperties swaggerProperties) {
            // base-path处理
            if (swaggerProperties.getBasePath().isEmpty()) {
                swaggerProperties.getBasePath().add(BASE_PATH);
            }
            // noinspection unchecked
            List<Predicate<String>> basePath = new ArrayList<Predicate<String>>();
            swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path)));
    
            // exclude-path处理
            if (swaggerProperties.getExcludePath().isEmpty()) {
                swaggerProperties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH);
            }
    
            List<Predicate<String>> excludePath = new ArrayList<>();
            swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
            
           ApiSelectorBuilder builder = new Docket(DocumentationType.OAS_30)
                    .host(swaggerProperties.getHost())
                    .apiInfo(apiInfo(swaggerProperties))
                    .groupName(swaggerProperties.getGroupName())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()));
    
            swaggerProperties.getBasePath().forEach(p -> builder.paths(PathSelectors.ant(p)));
            swaggerProperties.getExcludePath().forEach(p -> builder.paths(PathSelectors.ant(p).negate()));
    
            return builder.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();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    在 annotation中创建使用swagger的注解

    annotation文件夹下创建自定义注解

    import org.springframework.context.annotation.Import;
    
    import java.lang.annotation.*;
    
    @Target({ ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @EnableConfigurationProperties({SwaggerProperties.class})
    @Import({ SwaggerAutoConfiguration.class })
    public @interface EnableZhangSwagger
    {
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    加载SwaggerConfig特性配置

    1. resources 下创建META-INF 文件夹
    2. MeTA-INF 文件夹下创建spring 文件夹
    3. spring 文件夹下创建spring.factories文件。
      在此文件中声明以上的swagger配置文件所在路径,如下:
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
        zhang.common.swagger3.config.SwaggerProperties,\
        zhang.common.swagger3.config.SwaggerBeanPostProcessor,\
        zhang.common.swagger3.config.SwaggerWebConfiguration,\
        zhang.common.swagger3.config.SwaggerAutoConfiguration
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在接口模块中使用

    在user-server中使用。

    user-server的启动类中添加以下注解

    @SpringBootApplication 
    @EnableZhangSwagger// 使用自定义的swagger注解
    public class Server1Application {
        public static void main(String[] args) {
            SpringApplication.run(Server1Application.class,args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在接口项目的配置文件中配置swagger

    在项目中的resources 下的applicaiton.yaml下配置以下相关的内容

     # spring 配置
    spring:
      application:
        # 应用名称
        name: user-server
      mvc:
        pathmatch:
          matching-strategy: ant_path_matcher   #必须 设置 spring mvc 匹配规则
    
      # swagger配置
    swagger:
      enabled: true
      title: 测试标题
      groupName: 测试组
      description: 测试描述
      version: v.1.0.0
    	#  basePackage: 接口所在的控制器包名,不配置此项则自动使用@Api 等接口注解来识别
      contact:
        name: zhangjiantai
        url: www.zhangxiaosan.top
        email: 1554872492@qq.com
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    访问

    http://ip:user-server的端口/swagger-ui/index.htm 例如:
    http://localhost:8000/swagger-ui/index.htm

  • 相关阅读:
    vue在子组件中调用接口、点击按钮弹出窗口显示内容
    【Python】多进程 AttributeError: Can‘t pickle local object
    win10系统访问我的电脑&win10打开命令行
    某安全设备frp流量告警分析
    Google Earth Engine 教程——NDVI差异分析以及图像采集迭代分析
    华为云项目部署
    【C++】-- 多态
    关于Vue使用props传值遇到的一些问题
    高性能计算与多模态处理的探索之旅:英伟达GH200性能优化与GPT-4V的算力加速未来
    二刷算法训练营Day14 | 二叉树(1/9)
  • 原文地址:https://blog.csdn.net/qq_38313548/article/details/126526271