springboot swagar2 整合
时间: 2023-05-10 18:02:39 浏览: 59
SpringBoot是一个轻量级、没有侵入性的框架,能够快速地构建基于Spring的应用程序。Swagger2是一个强大的、完全开放源代码的API框架,具有自动生成API文档、可视化的API调试界面以及API接口管理的功能。
SpringBoot与Swagger2的结合可以大大地提高API接口的开发效率、方便API调试、提高接口的可维护性。下面是SpringBoot与Swagger2整合的具体步骤:
首先需要引入Swagger2的相关依赖,使用Maven可在pom.xml文件中加入以下内容:
```
<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>
```
然后需要在SpringBoot框架中启用Swagger2,在主类中加上@EnableSwagger2注解:
```
@SpringBootApplication
@EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
接着在配置文件中配置Swagger2相关的信息,在application.yml中加入以下内容:
```
swagger:
enable: true #是否开启swagger
title: 项目API接口文档 #文档标题
description: 项目API接口文档 #文档描述
version: 1.0.0 #文档版本
base-package: com.xxx.controller #接口所在的包
contact: #文档作者信息
name: xxx
email: xxx@xxx.com
url: xxx
license: #文档许可证信息
name: Apache License 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
```
最后在Controller类中使用Swagger2的注解来描述API接口,例如:
```
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
@GetMapping("/{id}")
@ApiOperation(value = "根据id获取用户信息", notes = "只能获取当前用户信息")
@ApiImplicitParam(name = "id", value = "用户id", dataType = "int", paramType = "path", required = true, defaultValue = "1")
public User getUserById(@PathVariable("id") Integer id) {
return userService.getUserById(id);
}
}
```
通过以上步骤,就可以在SpringBoot框架中集成Swagger2并生成API文档,方便API接口的开发、测试和维护。