springboot2整合swagger2
时间: 2025-06-20 20:04:10 浏览: 9
### 如何在 Spring Boot 2 中整合 Swagger 2
#### 添加 Maven 依赖
为了在 Spring Boot 项目中启用 Swagger 功能,在 `pom.xml` 文件中需添加如下两个依赖:
```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>
```
这些依赖提供了构建 API 文档以及 UI 页面所需的功能[^1]。
#### 创建 Swagger 配置类
创建一个新的 Java 类作为 Swagger 的配置文件,通常命名为 `SwaggerConfig.java`。此配置类应包含必要的注解以激活并自定义 Swagger 行为:
```java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
```
通过上述代码片段中的 `@Configuration` 注解表明这是一个配置类;而 `@EnableSwagger2` 则用来开启 Swagger 支持[^2]。
对于更详细的定制化需求,可以进一步扩展这个配置类的内容,比如设置基本信息、联系人信息等。
#### 使用 Swagger 注解增强控制器
为了让生成的文档更加清晰易懂,建议开发者利用一系列特定于 Swagger 的注解来描述 RESTful 接口的行为及其参数。常见的有:
- `@Api`: 描述整个 Controller;
- `@ApiOperation`: 描述某个 HTTP 方法的具体操作;
- `@ApiParam`: 对单个方法参数提供额外解释;
- `@ApiResponse`: 定义可能产生的响应码及消息体结构;
- `@ApiModel`: 当返回对象复杂时可对其字段做标注[^3]。
例如:
```java
@RestController
@RequestMapping("/api/v1/users")
@Api(tags = {"User Management"})
public class UserController {
@GetMapping("/{id}")
@ApiOperation(value = "Get user by ID", notes = "Returns a single user.")
public ResponseEntity<UserDTO> getUserById(@PathVariable("id") Long id) {
// Implementation here...
}
}
```
完成以上步骤之后重启应用程序即可访问默认路径 `/swagger-ui.html` 查看在线接口文档界面[^4]。
阅读全文
相关推荐


















