swagger2(spring boot 版本需低于2.5.6)
-
pom.xml 加入依赖
<!--swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!--swagger-ui.html模式 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!--doc.html模式 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.2</version>
-
添加配置类
/** * swagger配置类 * * @author dong * @date 2022/6/15 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket( DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //为当前包路径,控制器类包 .apis( RequestHandlerSelectors.basePackage("com.dong.controller")) .paths( PathSelectors.any()) .build(); } //构建 api文档的详细信息函数,注意这里的注解引用的是哪个 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("Spring Boot 集成 Swagger2 测试接口文档") //创建人 .contact(new Contact("dong", "https://github.com/dongdong987", "dongdong9780@163.com")) //版本号 .version("1.0") //描述 .description("API 描述") .build(); } }
- 加入相关注解
- 启动项目访问 http://localhost:8080/swagger-ui.html
swagger3
-
pom.xml
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
-
配置类
@Configuration @EnableOpenApi public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket( // 设置使用 OpenApi 3.0 规范 DocumentationType.OAS_30) // 配置项目基本信息 .apiInfo(apiInfo()) // 设置项目组名 .groupName("研发后端组") // 选择那些路径和api会生成document .select() // 对所有api进行监控 .apis(RequestHandlerSelectors.any()) // 扫描的路径包,用于指定路径接口扫描设置 .apis(RequestHandlerSelectors.basePackage("com.dong.controller")) // 对所有路径进行监控 .paths(PathSelectors.any()) // 忽略以"/error"开头的路径,可以防止显示如404错误接口 .paths(PathSelectors.regex("/error.*").negate()) // 忽略以"/actuator"开头的路径 .paths(PathSelectors.regex("/actuator.*").negate()) .build(); } //生成接口信息,包括标题、联系人等 private ApiInfo apiInfo() { return new ApiInfoBuilder() // 文档标题 .title("后端服务接口文档") // 文档描述 .description("客户端相关操作接口") // 文档版本 .version("0.0.1") // 设置许可声明信息 .license("Apache LICENSE 2.0") // 设置许可证URL地址 .licenseUrl("https://XXX.com") // 设置管理该API人员的联系信息 .contact(new Contact("dong", "https://XXX.com", "978081331@qq.com")) .build(); } }
-
application.xml
#默认是true,设置为false可以关闭swagger开关 springfox.documentation.enabled=true #spring boot 版本大于2.5.6的配置 #因为Springfox 使用的路径匹配是基于AntPathMatcher的, #而Spring Boot 2.6.X使用的是PathPatternMatcher,修改该配置 spring.mvc.pathmatch.matching-strategy=ant_path_matcher
添加相关接口