1. 添加 Swagger 依赖
在 pom.xml
文件中添加 Swagger 依赖项:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2. 配置 Swagger
在 src/main/java/com/example/demo/config
目录下创建一个新的配置类 SwaggerConfig.java
:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
}
3. 添加注解到控制器
为了让 Swagger 识别 API,你可以在控制器类和方法上添加注解。例如,在 UserController.java
中:
package com.example.demo.controller;
import com.example.demo.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Api(tags = "User Management")
@RestController
@RequestMapping("/api/users")
public class UserController {
private List<User> users = new ArrayList<>();
@ApiOperation(value = "Get all users", notes = "Returns a list of all users")
@GetMapping
public List<User> getAllUsers() {
return users;
}
@ApiOperation(value = "Get user by ID", notes = "Returns a single user by ID")
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
}
@ApiOperation(value = "Create a new user", notes = "Creates a new user and returns the created user")
@PostMapping
public User createUser(@RequestBody User user) {
users.add(user);
return user;
}
@ApiOperation(value = "Update an existing user", notes = "Updates a user's information by ID")
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
User user = getUserById(id);
if (user != null) {
user.setName(updatedUser.getName());
user.setEmail(updatedUser.getEmail());
}
return user;
}
@ApiOperation(value = "Delete a user", notes = "Deletes a user by ID")
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
users.removeIf(user -> user.getId().equals(id));
}
}
4. 访问 Swagger UI
启动 Spring Boot 应用程序后,可以通过浏览器访问 Swagger UI,通常是通过以下 URL:
http://localhost:8080/swagger-ui/
Swagger UI 是一个交互式界面,展示了所有的 API 端点和方法,你可以直接在页面上进行 API 请求测试。
5. 生成静态文档(可选)
如果你需要生成静态的 API 文档,可以使用 Swagger 的代码生成工具或其他第三方工具,例如 Swagger2Markup。通过这些工具,可以将 API 文档生成 HTML、PDF、Asciidoc 等格式的文档。
6. 配置 Swagger 文档的详细信息(可选)
如果你希望为 Swagger 文档添加更多详细信息,例如 API 标题、描述、版本等,可以在 SwaggerConfig
中添加如下配置:
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("User Management API")
.description("This API allows to perform CRUD operations on users")
.version("1.0.0")
.build();
}