1、maven添加依赖
<!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
2、添加配置类
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.oas.annotations.EnableOpenApi; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; @Configuration @EnableOpenApi public class Swagger2Config implements WebMvcConfigurer { /** * 是否开启swagger配置,生产环境需关闭 */ @Value("${swagger.enabled}") private boolean enable; @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30).pathMapping("/") .enable(enable) .apiInfo(this.apiInfo()) .select() // 指定需要发布到Swagger的接口目录,不支持通配符 .apis(RequestHandlerSelectors.basePackage("com.myblog.blogboot.controller")) .paths(PathSelectors.any()) .build() // 支持的通讯协议集合 .protocols(this.newHashSet("https", "http")); } /** * 项目信息 */ private ApiInfo apiInfo() { return new ApiInfoBuilder().title("Swagger Api Doc") .description("SpringBoot后台接口") .contact(new Contact("user", null, "durtime@qq.com")) .version("Application Version: 1.0.0") .build(); } @SafeVarargs private final <T> Set<T> newHashSet(T... ts) { if (ts.length > 0) { return new LinkedHashSet<>(Arrays.asList(ts)); } return null; } }
3、添加自定义配置
# ===== 自定义swagger配置 ===== # swagger: enabled: true
就可以基本的使用了
在使用swagger的时候,通常需要使用【@ApiParam】注解指定接口中参数的名字,特别是接口是post请求且参数使用了@RequestParam注解时
注意
3.0.0版本:需添加starter
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
3.0.0版本以下:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
配置Config
- 3.0.0之前版本需使用@EnableSwagger2注解
- 3.0.0版本则不需要@EnableSwagger2注解,取而代之是@EnableOpenApi
ui界面地址的改变
- 3.0.0之前的版本访问是:/swagger-ui.html
- 3.0.0版本访问是:/swagger-ui/index.html
Docket(文档摘要信息)的文件类型配置不同
新版本配置的是 OAS_3,而老版本是 SWAGGER_2;
如果配置了拦截器,需要放开,添加配置
@Configuration public class MvcConfig implements WebMvcConfigurer { @Autowired JWTInterceptor jwtInterceptor; public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor) .addPathPatterns("/**") .excludePathPatterns("/swagger**/**", "/webjars/**", "/v3/**", "/doc.html"); } }
其他详细见官网