比試一下:Swagger3就是比2簡單粗暴
接口文檔總是很煩人,我曾經(jīng)嘗試過用Postman來編寫和分享項(xiàng)目文檔,感覺還不錯(cuò)。但是最近項(xiàng)目緊,我沒有額外的時(shí)間可以花在它上面,這也導(dǎo)致我嘗試YApi(另外一種文檔)的計(jì)劃泡湯了。嗯,目前沒有比Swagger更快、更傻瓜的工具,雖然它有嚴(yán)重的代碼污染。先拿這個(gè)對(duì)付一陣時(shí)間,等閑暇時(shí)間再玩YApi。
Swagger3集成
Swagger目前最新版本是3.0.0,在Spring Boot應(yīng)用中集成Swagger3比老的Swagger2簡單多了,它提供了一個(gè)Starter組件。
- <dependency>
- <groupId>io.springfox</groupId>
- <artifactId>springfox-boot-starter</artifactId>
- <version>3.0.0</version>
- </dependency>
就這就可以了,簡單不?
至于有的教程說還要開啟注解@EnableOpenApi,完全不需要。因?yàn)樵趕pringfox-boot-starter-3.0.0.jar下你可以找到一個(gè)spring.factories,熟悉Spring Boot的同學(xué)都知道這個(gè)是一個(gè)Spring Boot 特有的SPI文件,能夠自動(dòng)的發(fā)現(xiàn)并注冊(cè)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 {
- }
一些發(fā)現(xiàn)
我們找到了關(guān)鍵的一個(gè)地方@ConditionalOnProperty注解聲明了當(dāng)springfox.documentation.enabled為true時(shí)啟用配置,而且默認(rèn)值就是true。這非常有用,Swagger僅僅建議在開發(fā)階段使用,這個(gè)正好是個(gè)開關(guān)。另外有時(shí)候我們自定義配置的時(shí)候最好把這個(gè)開關(guān)也加上:
- // 自定義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("更多請(qǐng)咨詢felord.cn")
- .contact(new Contact("碼農(nóng)小胖哥", "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 {
- }
上面的兩個(gè)導(dǎo)入類都可以在OpenApiAutoConfiguration找到,所以Swagger3提供的是全自動(dòng)的集成。
和全局統(tǒng)一參數(shù)不兼容
如果你使用了統(tǒng)一返回體封裝器來標(biāo)準(zhǔn)化Spring MVC接口的統(tǒng)一返回
- /**
- * 返回體統(tǒng)一封裝器
- *
- * @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);
- }
- }
你會(huì)發(fā)現(xiàn)Swagger3會(huì)報(bào)Unable to infer base url……的錯(cuò)誤,這是因?yàn)榻y(tǒng)一返回體影響到了Swagger3的一些內(nèi)置接口。解決方法是@RestControllerAdvice控制好生效的包范圍,也就是配置其basePackages參數(shù)就行了,這個(gè)潛在的沖突浪費(fèi)我了一個(gè)多小時(shí)。
安全框架放行
如果你使用安全框架,Swagger3的內(nèi)置接口就會(huì)訪問受限,我們需要排除掉。Spring Security是這么配置的:
- @Override
- public void configure(WebSecurity web) throws Exception {
- //忽略swagger3所需要用到的靜態(tài)資源,允許訪問
- 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就能正常的渲染和訪問了。
總結(jié)
今天分享了一些swagger3的配置心得,希望能夠幫助你上手最新的swagger3文檔工具。
本文轉(zhuǎn)載自微信公眾號(hào)「碼農(nóng)小胖哥」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系碼農(nóng)小胖哥公眾號(hào)。