比试一下:Swagger3就是比2简单粗暴

开发 前端
接口文档总是很烦人,我曾经尝试过用Postman来编写和分享项目文档,感觉还不错。但是最近项目紧,我没有额外的时间可以花在它上面,这也导致我尝试YApi(另外一种文档)的计划泡汤了。

[[392715]]

接口文档总是很烦人,我曾经尝试过用Postman来编写和分享项目文档,感觉还不错。但是最近项目紧,我没有额外的时间可以花在它上面,这也导致我尝试YApi(另外一种文档)的计划泡汤了。嗯,目前没有比Swagger更快、更傻瓜的工具,虽然它有严重的代码污染。先拿这个对付一阵时间,等闲暇时间再玩YApi。

Swagger3集成

Swagger目前最新版本是3.0.0,在Spring Boot应用中集成Swagger3比老的Swagger2简单多了,它提供了一个Starter组件。

  1. <dependency> 
  2.     <groupId>io.springfox</groupId> 
  3.     <artifactId>springfox-boot-starter</artifactId> 
  4.     <version>3.0.0</version> 
  5. </dependency> 

 

就这就可以了,简单不?

至于有的教程说还要开启注解@EnableOpenApi,完全不需要。因为在springfox-boot-starter-3.0.0.jar下你可以找到一个spring.factories,熟悉Spring Boot的同学都知道这个是一个Spring Boot 特有的SPI文件,能够自动的发现并注册Starter组件的配置。里面有这样的配置:

  1. # Auto Configure 
  2. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 
  3. springfox.boot.starter.autoconfigure.OpenApiAutoConfiguration 

顺藤摸瓜,找到总的配置类OpenApiAutoConfiguration:

  1. @Configuration 
  2. @EnableConfigurationProperties(SpringfoxConfigurationProperties.class) 
  3. @ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true
  4. @Import({ 
  5.     OpenApiDocumentationConfiguration.class, 
  6.     SpringDataRestConfiguration.class, 
  7.     BeanValidatorPluginsConfiguration.class, 
  8.     Swagger2DocumentationConfiguration.class, 
  9.     SwaggerUiWebFluxConfiguration.class, 
  10.     SwaggerUiWebMvcConfiguration.class 
  11. }) 
  12. @AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, 
  13.     HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) 
  14. public class OpenApiAutoConfiguration { 
  15.  

一些发现

我们找到了关键的一个地方@ConditionalOnProperty注解声明了当springfox.documentation.enabled为true时启用配置,而且默认值就是true。这非常有用,Swagger仅仅建议在开发阶段使用,这个正好是个开关。另外有时候我们自定义配置的时候最好把这个开关也加上:

  1. // 自定义swagger3文档信息 
  2. @Configuration 
  3. @ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true
  4. public class Swagger3Config { 
  5.     @Bean 
  6.     public Docket createRestApi() { 
  7.         return new Docket(DocumentationType.OAS_30) 
  8.                 .apiInfo(apiInfo()) 
  9.                 .select() 
  10.                 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 
  11.                 .paths(PathSelectors.any()) 
  12.                 .build(); 
  13.     } 
  14.  
  15.     private ApiInfo apiInfo() { 
  16.         return new ApiInfoBuilder() 
  17.                 .title("Swagger3接口文档"
  18.                 .description("更多请咨询felord.cn"
  19.                 .contact(new Contact("码农小胖哥""https://felord.cn""dax@felord.cn")) 
  20.                 .version("1.0.0"
  21.                 .build(); 
  22.     } 

如果你想在Swagger3中加入Json Web Token,可以参考这篇文章。

最开始我们提到Swagger3不需要使用@EnableOpenApi或者@EnableSwagger2开启,这里也能找到答案。

  1. @Import(OpenApiDocumentationConfiguration.class) 
  2. public @interface EnableOpenApi { 
  3. @Import(Swagger2DocumentationConfiguration.class) 
  4. public @interface EnableSwagger2 { 

上面的两个导入类都可以在OpenApiAutoConfiguration找到,所以Swagger3提供的是全自动的集成。

和全局统一参数不兼容

如果你使用了统一返回体封装器来标准化Spring MVC接口的统一返回

  1. /** 
  2.  * 返回体统一封装器 
  3.  * 
  4.  * @author n1 
  5.  */ 
  6. @RestControllerAdvice  
  7. public class RestBodyAdvice implements ResponseBodyAdvice<Object> { 
  8.     @Override 
  9.     public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { 
  10.         return !returnType.hasMethodAnnotation(IgnoreRestBody.class); 
  11.     } 
  12.  
  13.     @Override 
  14.     public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { 
  15.  
  16.         if (body == null) { 
  17.             return RestBody.ok(); 
  18.         } 
  19.         if (Rest.class.isAssignableFrom(body.getClass())) { 
  20.             return body; 
  21.         } 
  22.         return RestBody.okData(body); 
  23.     } 

你会发现Swagger3会报Unable to infer base url……的错误,这是因为统一返回体影响到了Swagger3的一些内置接口。解决方法是@RestControllerAdvice控制好生效的包范围,也就是配置其basePackages参数就行了,这个潜在的冲突浪费我了一个多小时。

安全框架放行

如果你使用安全框架,Swagger3的内置接口就会访问受限,我们需要排除掉。Spring Security是这么配置的:

  1. @Override 
  2. public void configure(WebSecurity web) throws Exception { 
  3.     //忽略swagger3所需要用到的静态资源,允许访问 
  4.     web.ignoring().antMatchers( "/swagger-ui.html"
  5.             "/swagger-ui/**"
  6.             "/swagger-resources/**"
  7.             "/v2/api-docs"
  8.             "/v3/api-docs"
  9.             "/webjars/**"); 

如果你使用的版本是Spring Security 5.4,你可以这么定制WebSecurity:

  1. @Bean 
  2. WebSecurityCustomizer swaggerWebSecurityCustomizer() { 
  3.     return (web) -> { 
  4.         web.ignoring().antMatchers(new String[]{"/swagger-ui.html""/swagger-ui/**""/swagger-resources/**""/v2/api-docs""/v3/api-docs""/webjars/**"}); 
  5.     }; 

更加方便简单图片,这样Swagger就能正常的渲染和访问了。

总结

 

 

 

今天分享了一些swagger3的配置心得,希望能够帮助你上手最新的swagger3文档工具。

本文转载自微信公众号「码农小胖哥」,可以通过以下二维码关注。转载本文请联系码农小胖哥公众号。

 

责任编辑:武晓燕 来源: 码农小胖哥
相关推荐

2022-07-21 11:04:53

Swagger3Spring

2010-12-06 09:10:02

LightSwitch

2023-02-08 09:02:05

VS Code摸鱼神器

2022-06-29 10:04:01

PiniaVuex

2020-10-15 11:18:13

Linux内核虚拟机

2022-03-02 10:53:22

Postman工具开发

2021-05-07 20:27:14

SpringBootSwagger3文档

2022-12-03 18:24:13

数据能力场景

2022-08-08 10:09:08

Vitest单元测试

2009-11-17 11:14:25

Oracle扩展

2021-01-21 07:31:11

Filter框架权限

2013-11-20 13:41:32

IE微软解决方法

2018-02-08 10:52:13

Kotlin语言代码

2010-06-13 17:57:23

局域网协议

2020-07-02 09:46:05

AI

2011-07-20 16:13:03

SQL Profile数据库

2024-01-31 08:23:54

2009-06-15 11:22:06

2015-11-12 10:32:27

前端后端分离

2011-08-22 15:19:25

点赞
收藏

51CTO技术栈公众号