微服务swagger公共模块(SpringBoot 2.7.7 Swagger 3.0.0)

一、SpringBoot和Swagger版本

SpringBoot:<spring-boot.version>2.7.7</spring-boot.version>

Swagger:<swagger.version>3.0.0</swagger.version>

二、创建common-swagger模块(module)

2.1 引入Swagger3依赖

<!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${swagger.version}</version>
        </dependency>

2.2 创建SwaggerConfig配置类

@Configuration
public class SwaggerConfig {

    /**
     * 配置Swagger信息
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                //设置组名
                .groupName("api-group")
                .select()
                //设置接口位置
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/");
    }

    /**
     * API信息:Swagger页面标题等信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //标题
                .title("API")
                //简介
                .description("")
                //服务条款
                .termsOfServiceUrl("")
                //版本
                .version("1.0").build();
    }

    /**
     * 解决Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
     * @return
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    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);
                }
            }
        };
    }

}

注:

  • springfoxHandlerProviderBeanPostProcessor()

    该方法为了解决启动Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException,有的说spring.mvc.pathmatch.matching-strategy=ant_path_matcher能解决,但配置后还是会异常(疑惑,求解)。

2.3 resources创建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件

在这里插入图片描述

文件配置com.xxx.common.swagger.config.SwaggerConfig

说明:当SpringBoot启动后,会找到META-INF->spring->org.springframework.boot.autoconfigure.AutoConfiguration.imports,并将配置的com.xxx.common.swagger.config.SwaggerConfig导入Spring容器,其他服务要使用Swagger只需引入Common-Swagger依赖就能生效。

2.4 启动成功,Swagger文档页面no operations defined in spec问题

  • 问题原因:

    Spring Boot 2.6以上版本的默认匹配策略是path-pattern-matcher,而Springfox默认SpringMVC 的路径匹配策略是ant-path-matcher,导致Springfox无法匹配到路径,从而无法找到接口信息。

  • 问题解决:

    # 在配置中心的共享配置文件配置
    spring:
      mvc:
        pathmatch:
          matching-strategy: ant_path_matcher
    

    有的说此配置能解决Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException,但配置后还是会异常(疑惑,求解)。

2.5 Swagger文档的关闭

  • 原因:

    在生产环境中,Swagger接口文档需要关闭,防止接口信息对外暴露。

  • 解决:

    # 在配置中心的共享配置文件配置
    # 关闭swagger
    springfox: 
      documentation: 
        enabled: false
    

三、业务模块引入common-swagger依赖

3.1 引入common-swagger依赖

<dependency>
    <groupId>com.xxx</groupId>
    <artifactId>common-swagger</artifactId>
    <version>${xxx-parent.version}</version>
</dependency>

3.2 配置共享文件

spring: 
  cloud:
    nacos:
      config:
        file-extension: yml
        shared-configs:
          - data-id: share-${spring.profiles.active}.yml

3.3 Swagger注解基础使用

  • @Api(tags = “类描述”):标注在类上,在Swagger会以tags的描述展示该类。
  • @ApiOperation(“接口描述”):标注在请求方法上,在Swagger文档上会展示接口信息。
  • @ApiModel(“参数类描述”):标注在参数类上,在Swagger文档的Schemas会以参数类描述展示。
  • @ApiModelProperty(value = “参数类成员变量描述”):标注在参数类的成员变量,在Swagger文档中的schemas会展示参数类成员变量描述,如果没有value,则只会展示参数定义名。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值