目的很简单,
1. 方便自己管理接口
2. 让前端开发人员方便,节省沟通成本
=》我也比较菜,没找到官方文档的整合资料
一、整合swagger3(spring boot版本2.5.2)
第1步在pom.xml 添加依赖
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
第2步写一个swagger3的配置类
@Configuration
@EnableOpenApi
public class Swagger3 {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
// 是否开启swagger
.enable(true)
.select()
// 过滤条件,扫描指定路径下的文件
.apis(RequestHandlerSelectors.basePackage("com.example.springboot04data"))
// 指定路径处理,PathSelectors.any()代表不过滤任何路径
//.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfo(
"Spring Boot 集成 Swagger3 测试",
"Spring Boot 集成 Swagger3 测试接口文档",
"v1.0",
"https://cunyu1943.github.io",
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
第3步,写一个Controller 的 测试类
@Api( tags = "用户管理相关的接口")
public class TestController {
@GetMapping("/test")
public String Test(){
return "调用成功了";
}
}
第4步:访问
它的访问方式:http://localhost:8080/swagger-ui/index.html
对,必须这样,跟swagger2不同,就要这样访问,不然会报错
详细的swagger3和swaager2对比,参考这篇文章:Spring Boot 使用 Swagger3 生成 API 接口文档 - 云+社区 - 腾讯云
二、 整合swagger2
导入依赖
<!--在springboot中使用swagger2,借助springfox-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
写swagger2配置类
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//是否开启 (true 开启 false隐藏。生产环境建议隐藏)
//.enable(false)
.select()
//扫描的路径包,设置basePackage会将包下的所有被@Api标记类的所有方法作为api
.apis(RequestHandlerSelectors.basePackage("com.example.jiGuangPush.controller"))
//指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//设置文档标题(API名称)
.title("SpringBoot-Swagger3集成和使用")
//文档描述
.description("接口说明")
//服务条款URL
.termsOfServiceUrl("http://localhost:8080/")
//版本号
.version("1.0.0")
.build();
}
}
测试接口controller 类
@Api(value = "测试接口", tags = "用户管理相关的接口", description = "用户测试接口")
public class TestController {
@GetMapping("/test")
public String Test(){
System.out.println("访问成功了");
return "调用成功了";
}
}
访问路径:http://localhost:8080/swagger-ui.html
详细的swagger3和swaager2对比,参考这篇文章:Spring Boot 使用 Swagger3 生成 API 接口文档 - 云+社区 - 腾讯云