SpringBoot 整合 Swagger3

一、添加pom依赖

<!-- Swagger3 -->
 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-boot-starter</artifactId>
     <version>3.0.0</version>
 </dependency>

二、创建配置类

@Configuration
@EnableOpenApi
public class SwaggerConfig {

    @Value("${server.port}")
    private String port ;

    @Bean
    public Docket createRestApi() {
        // 注意这里使用的时 OAS_30,这是Swagger3使用的DocumentationType
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                //是否开启 (true 开启  false隐藏。生产环境建议隐藏)
                //.enable(false)
                .select()
                //扫描的路径包,设置basePackage会将包下的所有被@Api标记类的所有方法作为api
                .apis(RequestHandlerSelectors.basePackage("com.bayzea.elemall.controller"))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //设置文档标题(API名称)
                .title("Swagger3接口规范")
                //文档描述
                .description("更多请咨询服务开发者XXX")
                //服务条款URL
                .termsOfServiceUrl("http://localhost:"+port+"/")
                //作者信息
                .contact(new Contact("作者", "作者地址", "作者邮箱"))
                //版本号
                .version("1.0.0")
                .build();
    }

    /**
     * @Description Spring高版本2.5.x 和 2.6.X版本以上会出现版本过高报错,添加该Bean可解决
     * @author Bayzea
     * @date 2022/4/21
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new 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);
                }
            }
        };
    }
}

三、Swagger常用注解

@Api:用在请求的类上,表示对类的说明

  tags="说明该类的作用,可以在UI界面上看到的注解"

  value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在请求的方法上,说明方法的用途、作用

  value="说明方法的用途、作用"

  notes="方法的备注说明"

@ApiImplicitParams:用在请求的方法上,表示一组参数说明

@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

    name:参数名

    value:参数的汉字说明、解释

    required:参数是否必须传

    paramType:参数放在哪个地方

      · header --> 请求参数的获取:@RequestHeader

      · query --> 请求参数的获取:@RequestParam

      · path(用于restful接口)--> 请求参数的获取:@PathVariable

      · body(不常用)

      · form(不常用)

    dataType:参数类型,默认String,其它值dataType="Integer"   

    defaultValue:参数的默认值

@ApiResponses:用在请求的方法上,表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

    code:数字,例如400

    message:信息,例如"请求参数没填好"

    response:抛出异常的类

@ApiModel:用于响应类上,表示一个返回响应数据的信息

      (这种一般用在post创建的时候,使用@RequestBody这样的场景,

      请求参数无法使用@ApiImplicitParam注解进行描述的时候)

@ApiModelProperty:用在属性上,描述响应类的属性

四、Controller 配置

@RestController
@RequestMapping("/AdminUser")
@Api(value = "测试接口", tags = "用户管理相关的接口", description = "用户测试接口")
public class AdminUserController {
    @Resource
    IAdminUserService adminUserService;

    @RequestMapping("getUser")
    @ApiOperation(value = "获取用户", notes = "获取用户")
    public Object getData() {
        return   adminUserService.getById(1);
    }
}

五、小提示

这次更新,移除了原来默认的swagger页面路径:http://ip:port/path/swagger-ui.html,
新增了两个可访问路径:http://ip:port/path/swagger-ui/index.html
和http://ip:port/path/swagger-ui/
通过调整日志级别,还可以看到新版本的swagger文档接口也有新增,除了以前老版本的文档接口/v2/api-docs之外,还多了一个新版本的/v3/api-docs接口。

六、踩坑

1.高版本Spring使用Swagger出现启动报空异常,解决方法在第二步配置项已解决

在这里插入图片描述

2.SwaggerUI无法显示修改mvc配置即可

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

版权声明:本文为qq_39236265原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。