比試一下:Swagger3就是比2簡單粗暴
接口文檔總是很煩人,我曾經嘗試過用Postman來編寫和分享項目文檔,感覺還不錯。但是最近項目緊,我沒有額外的時間可以花在它上面,這也導致我嘗試YApi(另外一種文檔)的計劃泡湯了。嗯,目前沒有比Swagger更快、更傻瓜的工具,雖然它有嚴重的代碼污染。先拿這個對付一陣時間,等閑暇時間再玩YApi。
Swagger3集成
Swagger目前最新版本是3.0.0,在Spring Boot應用中集成Swagger3比老的Swagger2簡單多了,它提供了一個Starter組件。
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-boot-starter</artifactId>
- <version>3.0.0</version>
- </dependency>
就這就可以了,簡單不?
至于有的教程說還要開啟注解@EnableOpenApi,完全不需要。因為在springfox-boot-starter-3.0.0.jar下你可以找到一個spring.factories,熟悉Spring Boot的同學都知道這個是一個Spring Boot 特有的SPI文件,能夠自動的發現并注冊Starter組件的配置。里面有這樣的配置:
- # Auto Configure
- org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
- springfox.boot.starter.autoconfigure.OpenApiAutoConfiguration
順藤摸瓜,找到總的配置類OpenApiAutoConfiguration:
- @Configuration
- @EnableConfigurationProperties(SpringfoxConfigurationProperties.class)
- @ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)
- @Import({
- OpenApiDocumentationConfiguration.class,
- SpringDataRestConfiguration.class,
- BeanValidatorPluginsConfiguration.class,
- Swagger2DocumentationConfiguration.class,
- SwaggerUiWebFluxConfiguration.class,
- SwaggerUiWebMvcConfiguration.class
- })
- @AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class,
- HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class })
- public class OpenApiAutoConfiguration {
- }
一些發現
我們找到了關鍵的一個地方@ConditionalOnProperty注解聲明了當springfox.documentation.enabled為true時啟用配置,而且默認值就是true。這非常有用,Swagger僅僅建議在開發階段使用,這個正好是個開關。另外有時候我們自定義配置的時候最好把這個開關也加上:
- // 自定義swagger3文檔信息
- @Configuration
- @ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)
- public class Swagger3Config {
- @Bean
- public Docket createRestApi() {
- return new Docket(DocumentationType.OAS_30)
- .apiInfo(apiInfo())
- .select()
- .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
- .paths(PathSelectors.any())
- .build();
- }
- private ApiInfo apiInfo() {
- return new ApiInfoBuilder()
- .title("Swagger3接口文檔")
- .description("更多請咨詢felord.cn")
- .contact(new Contact("碼農小胖哥", "https://felord.cn", "dax@felord.cn"))
- .version("1.0.0")
- .build();
- }
- }
如果你想在Swagger3中加入Json Web Token,可以參考這篇文章。
最開始我們提到Swagger3不需要使用@EnableOpenApi或者@EnableSwagger2開啟,這里也能找到答案。
- @Import(OpenApiDocumentationConfiguration.class)
- public @interface EnableOpenApi {
- }
- @Import(Swagger2DocumentationConfiguration.class)
- public @interface EnableSwagger2 {
- }
上面的兩個導入類都可以在OpenApiAutoConfiguration找到,所以Swagger3提供的是全自動的集成。
和全局統一參數不兼容
如果你使用了統一返回體封裝器來標準化Spring MVC接口的統一返回
- /**
- * 返回體統一封裝器
- *
- * @author n1
- */
- @RestControllerAdvice
- public class RestBodyAdvice implements ResponseBodyAdvice<Object> {
- @Override
- public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
- return !returnType.hasMethodAnnotation(IgnoreRestBody.class);
- }
- @Override
- public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
- if (body == null) {
- return RestBody.ok();
- }
- if (Rest.class.isAssignableFrom(body.getClass())) {
- return body;
- }
- return RestBody.okData(body);
- }
- }
你會發現Swagger3會報Unable to infer base url……的錯誤,這是因為統一返回體影響到了Swagger3的一些內置接口。解決方法是@RestControllerAdvice控制好生效的包范圍,也就是配置其basePackages參數就行了,這個潛在的沖突浪費我了一個多小時。
安全框架放行
如果你使用安全框架,Swagger3的內置接口就會訪問受限,我們需要排除掉。Spring Security是這么配置的:
- @Override
- public void configure(WebSecurity web) throws Exception {
- //忽略swagger3所需要用到的靜態資源,允許訪問
- web.ignoring().antMatchers( "/swagger-ui.html",
- "/swagger-ui/**",
- "/swagger-resources/**",
- "/v2/api-docs",
- "/v3/api-docs",
- "/webjars/**");
- }
如果你使用的版本是Spring Security 5.4,你可以這么定制WebSecurity:
- @Bean
- WebSecurityCustomizer swaggerWebSecurityCustomizer() {
- return (web) -> {
- web.ignoring().antMatchers(new String[]{"/swagger-ui.html", "/swagger-ui/**", "/swagger-resources/**", "/v2/api-docs", "/v3/api-docs", "/webjars/**"});
- };
- }
更加方便簡單圖片,這樣Swagger就能正常的渲染和訪問了。
總結
今天分享了一些swagger3的配置心得,希望能夠幫助你上手最新的swagger3文檔工具。
本文轉載自微信公眾號「碼農小胖哥」,可以通過以下二維碼關注。轉載本文請聯系碼農小胖哥公眾號。