SpringBoot整合Swagger
一、整合Swagger2
1、在pom.xml文件中引入依赖
这里使用的是Swagger2.9版本依赖
<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>
2、关注配置文件application.yml
在整合Swagger2版本,需要由于Spring Boot 2.6及更高版本使用的是 PathPatternMatcher ,所以需要修改配置
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
3、在项目中添加配置类SwaggerConfig.class
重要注解 @EnableSwagger2
/**
* 构建api文档的详细信息
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 设置页面标题
.title("Spring Boot集成 Swagger2接口总览")
// 设置页面描述
.description("这是一个简短的页面描述")
// 设置联系方式
.contact("空山万籁," + "优快云:http://blog.youkuaiyun.com/KS_wl")
// 设置版本
.version("0.1")
// 构建
.build();
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// 指定构建api文档的详细信息的方法:apiInfo()
.apiInfo(apiInfo())
.select()
// 指定要生成api接口的包路径,这里把controller作为包路径,生成controller中的所有接口
.apis(RequestHandlerSelectors.basePackage("com.study.controller"))
.paths(PathSelectors.any())
.build();
}
4、具体的Controller类
@Api(tags = "j简单测试接口")
@RestController
@RequestMapping("/swagger")
public class TestController {
@GetMapping("/get/{id}")
public JsonResult<User> getUserinof(@PathVariable @ApiParam(value = "用户唯一标识") int id) {
User user = new User(1, "张三", "123456");
return new JsonResult(user);
}
/*
@Api 注解用于类上,表示标识这个类是 swagger 的资源。
@ApiOperation 注解用于方法,表示一个 http 请求的操作。
@ApiParam 注解用于参数上,用来标明参数信息。
*/
}
二、SpringBoot整合Swagger3
1、整合Swagger3
大致步骤与Swagger2相同,只有局部细节不同
依赖部分
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
注解部分
在SwaggerConfig的配置类上,改用了@EnableOpenApi,在下面的代码中 new Docket() 中修改参数为DocumentationType.OAS_30
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/*这是 Swagger2.x 的配置类*/
/*省略内容部分*/
@Bean
public Docket createRestApi(){
/*这里使用的DocumentationType.SWAGGER_2 */
return new Docket(DocumentationType.SWAGGER_2).....;
}
}
@Configuration
@EnableOpenApi
public class SwaggerConfig {
/*这是 Swagger3.0 的配置类*/
/*省略内容部分*/
@Bean
public Docket createRestApi(){
/*这里使用的DocumentationType.OAS_30 */
return new Docket(DocumentationType.OAS_30)....;
}