总结 : SpringBoot 项目中使用Swagger2

xiaoxiao2025-04-27  11

在springboot项目中想使用swagger2作为接口查看文档:

1. 使用的jar包 :在pom.xml文件中 引入下面的依赖

<!--引入Swagger2的依赖--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency>

2. 在启动类上面添加下面的注解,此时就可以打开 链接 http://127.0.0.1:8081/swagger-ui.html#/

@EnableSwagger2

3.但是经过前两步骤之后 在swagger页面会出现 BaseController 等不必要信息,则可以在代码中写一个配置类,将其过滤掉:

/** * 此配置文件: * 解决访问swaggerUI接口文档显示basic-error-controler问题 * */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .pathMapping("/") .select() // 选择那些路径和api会生成document .apis(RequestHandlerSelectors.any())// 对所有api进行监控 //不显示错误的接口地址 .paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控 .paths(PathSelectors.regex("/.*"))// 对根下所有路径进行监控 .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("API接口文档") .license("The Apache License, Version 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .version("v1.0") .build(); } }

经过上面3步之后可以正常使用swagger页面查看接口信息(尽量使用swagger的一些注解及@Api等)

转载请注明原文地址: https://www.6miu.com/read-5029233.html

最新回复(0)