Khi mới bắt đầu học Spring Boot, mình từng gặp khó khăn khi tiếp cận RESTful service và Swagger. Sau một thời gian tìm hiểu, mọi thứ trở nên đơn giản hơn rất nhiều. Trong quá trình làm một dự án quản lý linh kiện, mình đã áp dụng phong cách RESTful chuẩn hóa theo hướng dẫn từ video. Việc sử dụng giao diện thống nhất giúp giảm thiểu các rắc rối không cần thiết.
Swagger là thư viện thường dùng trong phát triển nhóm, nhưng mình thấy nó thú vị và đã thử tích hợp. Dưới đây là các bước triển khai cùng kết quả hiển thị.
1. Thêm phụ thuộc Maven
Thêm hai dependency vào file pom.xml để kích hoạt Swagger 2:
<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. Cấu hình Swagger
Tạo một class cấu hình để kích hoạt Swagger và định nghĩa thông tin API:
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
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 createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Dự án quản lý linh kiện")
.description("API Swagger cho dự án quản lý linh kiện")
.version("1.0")
.build();
}
}
3. Truy cập giao diện Swagger
Sau khi chạy ứng dụng, bạn có thể truy cập giao diện Swagger UI qua địa chỉ:
http://localhost:8080/swagger-ui.html
Tại đây, tất cả các endpoint trong package com.example.controller sẽ được liệt kê và có thể test trực tiếp.
Kết quả
Swagger giúp hiển thị danh sách API một cách trực quan, hỗ trợ thao tác gửi request và xem response ngay trên trình duyệt, rất hữu ích cho việc phát triển và kiểm thử.