Để xây dựng tài liệu API trực quan và hỗ trợ thử nghiệm giao diện, việc tích hợp Swagger2 vào ứng dụng Spring Boot là bước cần thiết. Dưới đây là quy trình thiết lập chi tiết.
1. Thêm các dependency vào file 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>
2. Tạo lớp cấu hình Swagger
Lớp này chịu trách nhiệm khởi tạo bean Docket và cấu hình thông tin cơ bản cho API.
@EnableSwagger2
@Configuration
public class ApiDocumentationConfig {
@Value("${api.swagger.enabled:false}")
private boolean isDocumentationEnabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(isDocumentationEnabled)
.apiInfo(getApiInfo())
.select()
// Quét các controller trong package cụ thể
.apis(RequestHandlerSelectors.basePackage("com.example.project"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
.title("Tài liệu API Hệ thống")
.description("Các giao diện lập trình ứng dụng")
.version("1.0")
.build();
}
}
3. Cấu hình trong application.properties
# Bật/tắt Swagger (Nên tắt khi chạy môi trường production)
api.swagger.enabled=true
4. Cấu hình mapping tài nguyên tĩnh
Nếu dự án sử dụng WebMvcConfigurationSupport, bạn cần khai báo đường dẫn cho các tệp tĩnh của Swagger UI để trình duyệt có thể truy cập được.
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// Cấu hình các tài nguyên tĩnh khác của dự án
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/static/");
// Cấu hình Swagger UI
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
5. Sử dụng Annotation trong Controller
Để Swagger hiển thị thông tin chi tiết cho từng API, hãy sử dụng các annotation như bên dưới:
@Api(tags = "Quản lý xác thực")
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
@ApiOperation(value = "Đăng nhập hệ thống", notes = "Trả về token nếu xác thực thành công")
@PostMapping("/login")
public Map<String, Object> processLogin(
@ApiParam(value = "Tên đăng nhập", required = true) @RequestParam String username,
@ApiParam(value = "Mật khẩu", required = true) @RequestParam String password) {
Map<String, Object> response = new HashMap<>();
try {
// Giả lập logic kiểm tra
if ("admin".equals(username)) {
response.put("status", "success");
response.put("token", "dummy-jwt-token");
} else {
throw new RuntimeException("Tài khoản không tồn tại");
}
} catch (Exception ex) {
response.put("status", "error");
response.put("message", ex.getMessage());
}
return response;
}
@ApiOperation(value = "API cũ không dùng nữa")
@Deprecated
@GetMapping("/legacy")
public String legacyMethod() {
return "Phương thức này đã bị loại bỏ";
}
}
6. Truy cập giao diện Swagger
Khởi động ứng dụng và truy cập vào đường dẫn:
http://localhost:8080/swagger-ui.html
7. Các Annotation thường gặp khác
@Api: Đặt ở cấp lớp Controller, mô tả nhóm chức năng.@ApiOperation: Đặt ở cấp phương thức, mô tả hành động của API.@ApiParam: Mô tả chi tiết các tham số trong request.@ApiModel: Dùng cho các class POJO/Entity để mô tả dữ liệu đầu vào/ra.@ApiModelProperty: Mô tả các trường (field) bên trong class được đánh dấu@ApiModel.@ApiIgnore: Bỏ qua không hiển thị class hoặc method này lên tài liệu.@ApiImplicitParam&@ApiImplicitParams: Dùng để mô tả các tham số không định nghĩa rõ ràng bằng các annotation khác.
Việc sử dụng @Deprecated trên một phương thức sẽ khiến Swagger hiển thị mục đó dưới dạng bị gạch bỏ, giúp các nhà phát triển dễ dàng nhận diện các API không nên sử dụng.