Spring Boot là framework Java phổ biến nhất hiện nay để xây dựng các ứng dụng web và microservices. Với cơ chế auto-configuration và embedded server, bạn có thể tạo một REST API hoàn chỉnh chỉ trong vài phút mà không cần cấu hình phức tạp.
Trong bài này, chúng ta sẽ xây dựng một API quản lý sản phẩm (Product API) đơn giản để minh họa các khái niệm quan trọng.
Cấu Trúc Project Spring Boot Chuẩn
Một project Spring Boot theo chuẩn layered architecture thường có các package sau:
- controller – Xử lý HTTP request/response
- service – Chứa business logic
- repository – Giao tiếp với database
- model/entity – Định nghĩa cấu trúc dữ liệu
- dto – Data Transfer Object để tách biệt API và DB model
- exception – Xử lý ngoại lệ tập trung
Khởi Tạo Project Với Spring Initializr
Truy cập start.spring.io và chọn các dependency sau:
- Spring Web
- Spring Data JPA
- H2 Database (hoặc MySQL Driver)
- Lombok
- Spring Boot DevTools
Tạo Entity và Repository
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SanPham {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String ten;
private double gia;
private int soLuong;
}
@Repository
public interface SanPhamRepository
extends JpaRepository<SanPham, Long> {
List<SanPham> findByTenContainingIgnoreCase(String ten);
}
Tạo Service Layer
@Service
@RequiredArgsConstructor
public class SanPhamService {
private final SanPhamRepository repository;
public List<SanPham> layTatCa() {
return repository.findAll();
}
public SanPham layTheoId(Long id) {
return repository.findById(id)
.orElseThrow(() -> new RuntimeException("Không tìm thấy sản phẩm"));
}
public SanPham taaMoi(SanPham sanPham) {
return repository.save(sanPham);
}
public void xoa(Long id) {
repository.deleteById(id);
}
}
Tạo REST Controller
@RestController
@RequestMapping("/api/san-pham")
@RequiredArgsConstructor
public class SanPhamController {
private final SanPhamService service;
@GetMapping
public ResponseEntity<List<SanPham>> layTatCa() {
return ResponseEntity.ok(service.layTatCa());
}
@GetMapping("/{id}")
public ResponseEntity<SanPham> layTheoId(@PathVariable Long id) {
return ResponseEntity.ok(service.layTheoId(id));
}
@PostMapping
public ResponseEntity<SanPham> taoMoi(@RequestBody SanPham sp) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(service.taaMoi(sp));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> xoa(@PathVariable Long id) {
service.xoa(id);
return ResponseEntity.noContent().build();
}
}
Các HTTP Method Thường Dùng Trong REST API
| Method | Endpoint | Chức năng |
|---|---|---|
| GET | /api/san-pham | Lấy danh sách tất cả sản phẩm |
| GET | /api/san-pham/{id} | Lấy 1 sản phẩm theo ID |
| POST | /api/san-pham | Tạo sản phẩm mới |
| PUT | /api/san-pham/{id} | Cập nhật sản phẩm |
| DELETE | /api/san-pham/{id} | Xóa sản phẩm |
Xử Lý Lỗi Tập Trung Với @ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> xuLyLoi(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
}
Kết Luận
Spring Boot giúp bạn xây dựng REST API nhanh chóng và có cấu trúc rõ ràng. Hãy nắm chắc luồng Controller → Service → Repository, và luôn xử lý ngoại lệ một cách tập trung để API của bạn dễ bảo trì và mở rộng về sau.
]]>