Các annotation trong Spring Boot
Dưới đây là một bài tổng hợp chi tiết về các nhóm annotation trong Spring Boot, kèm theo ví dụ minh họa và một sơ đồ mindmap Mermaid ở phần đầu để tóm tắt.
1. Nhóm Annotation Cấu Hình
@SpringBootApplication
- Giải thích: Là annotation chủ chốt khi khởi động một ứng dụng Spring Boot. Nó kết hợp 3 annotation:
- @Configuration: Đánh dấu lớp là nguồn định nghĩa bean.
- @EnableAutoConfiguration: Kích hoạt cơ chế tự động cấu hình.
- @ComponentScan: Quét và đăng ký các bean trong package hiện hành và các package con.
- Ví dụ:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration và @Bean
- Giải thích:
- @Configuration: Đánh dấu lớp là cấu hình Spring, nơi bạn định nghĩa các bean.
- @Bean: Được sử dụng bên trong lớp có @Configuration để khai báo bean.
- Ví dụ:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
2. Nhóm Annotation Quản Lý Bean và Dependency Injection
@Component, @Service, @Repository, @Controller
- Giải thích:
- @Component: Annotation tổng quát để đánh dấu một bean.
- @Service: Dùng để đánh dấu lớp cung cấp logic nghiệp vụ.
- @Repository: Dùng cho lớp thao tác dữ liệu, tích hợp với cơ chế exception translation.
- @Controller: Dùng để định nghĩa controller trong mô hình MVC.
- Ví dụ:
@Service
public class UserService {
// Logic nghiệp vụ liên quan đến người dùng
}
@Repository
public class UserRepository {
// Thao tác dữ liệu cho người dùng
}
@Autowired và @Qualifier
- Giải thích:
- @Autowired: Tự động tiêm bean theo kiểu (by type).
- @Qualifier: Dùng khi có nhiều bean cùng kiểu để xác định bean cụ thể cần tiêm.
- Ví dụ:
@Component
public class OrderController {
private final OrderService orderService;
@Autowired
public OrderController(@Qualifier("orderServiceImpl") OrderService orderService) {
this.orderService = orderService;
}
}
3. Nhóm Annotation Cho Web
@RestController và @Controller
- Giải thích:
- @RestController: Kết hợp @Controller và @ResponseBody, dùng cho các RESTful API.
- @Controller: Dùng cho ứng dụng web theo mô hình MVC, thường trả về view.
- Ví dụ:
@RestController
public class ProductController {
@GetMapping("/products")
public List<Product> getAllProducts() {
// Trả về danh sách sản phẩm dưới dạng JSON
return productService.findAll();
}
}
@RequestMapping và các annotation con
- Giải thích:
- @RequestMapping: Ánh xạ URL đến phương thức controller.
- @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Các annotation chuyên biệt cho các phương thức HTTP tương ứng.
- Ví dụ:
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home"; // Trả về tên view
}
}
@PathVariable, @RequestParam, @RequestBody
- Giải thích:
- @PathVariable: Lấy giá trị từ phần đường dẫn URL.
- @RequestParam: Lấy giá trị từ query string.
- @RequestBody: Ép kiểu dữ liệu JSON từ request body thành đối tượng Java.
- Ví dụ:
@RestController
public class UserController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long id) {
return userService.findById(id);
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.save(user);
}
}
4. Nhóm Annotation Liên Quan Đến Giao Dịch (Transaction)
@Transactional
- Giải thích: Dùng để đánh dấu phương thức hoặc lớp cần thực hiện giao dịch. Khi xảy ra lỗi, toàn bộ transaction sẽ được rollback.
- Ví dụ:
@Service
public class AccountService {
@Transactional
public void transfer(Long fromAccountId, Long toAccountId, Double amount) {
accountRepository.debit(fromAccountId, amount);
accountRepository.credit(toAccountId, amount);
}
}
5. Nhóm Annotation Liên Quan Đến Caching
@Cacheable, @CachePut, @CacheEvict
- Giải thích:
- @Cacheable: Lưu kết quả trả về của phương thức, dùng lại khi cùng tham số.
- @CachePut: Cập nhật cache sau khi phương thức thực thi.
- @CacheEvict: Xóa bỏ cache khi có thay đổi dữ liệu.
- Ví dụ:
@Service
public class ProductService {
@Cacheable("products")
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
}
6. Nhóm Annotation Liên Quan Đến Scheduling
@Scheduled và @EnableScheduling
- Giải thích:
- @EnableScheduling: Kích hoạt chức năng lập lịch trong Spring Boot.
- @Scheduled: Đánh dấu phương thức cần thực hiện định kỳ theo lịch trình.
- Ví dụ:
@Configuration
@EnableScheduling
public class SchedulingConfig {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("Báo cáo thời gian: " + LocalDateTime.now());
}
}
7. Nhóm Annotation Liên Quan Đến Kiểm Thử (Testing)
@SpringBootTest, @WebMvcTest, @DataJpaTest
- Giải thích:
- @SpringBootTest: Tạo môi trường Spring Boot đầy đủ để chạy test.
- @WebMvcTest: Test các thành phần liên quan đến web (controller).
- @DataJpaTest: Tập trung test các repository và JPA.
- Ví dụ:
@SpringBootTest
public class ApplicationTests {
@Autowired
private UserService userService;
@Test
public void testUserService() {
// Kiểm tra logic nghiệp vụ
}
}
8. Nhóm Annotation Liên Quan Đến JPA/Hibernate
@Entity, @Table, @Id, @GeneratedValue, @Column
- Giải thích:
- @Entity: Đánh dấu lớp là một entity của JPA.
- @Table: Chỉ định tên bảng trong cơ sở dữ liệu.
- @Id: Đánh dấu trường làm khóa chính.
- @GeneratedValue: Chỉ định chiến lược tạo giá trị cho khóa chính.
- @Column: Cấu hình cột trong bảng.
- Ví dụ:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username", nullable = false, unique = true)
private String username;
// Getter, Setter và các phương thức khác
}
Các Annotation Quan Hệ (Relationship)
- Giải thích:
- @OneToOne, @OneToMany, @ManyToOne, @ManyToMany: Định nghĩa các mối quan hệ giữa các entity.
- Ví dụ:
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}
9. Nhóm Annotation Liên Quan Đến AOP
@Aspect và các annotation AOP khác
- Giải thích:
- @Aspect: Đánh dấu lớp chứa các advice (lời khuyên) dùng để cắt xén hành vi của ứng dụng.
- Các annotation như @Before, @After, @Around, @AfterReturning, @AfterThrowing được dùng để định nghĩa thời điểm chạy advice.
- Ví dụ:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Bắt đầu thực hiện: " + joinPoint.getSignature().getName());
}
}
10. Nhóm Annotation Liên Quan Đến Bảo Mật
@Secured, @PreAuthorize, @PostAuthorize, @RolesAllowed
- Giải thích:
- @Secured: Chỉ định các role được phép truy cập.
- @PreAuthorize, @PostAuthorize: Dùng biểu thức để kiểm tra quyền trước hoặc sau khi phương thức thực thi.
- @RolesAllowed: Tương tự @Secured, thường dùng với JSR-250.
- Ví dụ:
@RestController
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminAccess() {
return "Chỉ admin mới có thể truy cập";
}
}
11. Nhóm Annotation Khác
@Value, @Profile, @Conditional, @Import
- Giải thích:
- @Value: Tiêm giá trị từ file cấu hình (application.properties/yaml) vào biến.
- @Profile: Xác định bean hoặc cấu hình chỉ áp dụng cho một profile nhất định (dev, prod, …).
- @Conditional: Điều kiện tạo bean dựa trên một điều kiện cụ thể, có các biến thể như @ConditionalOnProperty, @ConditionalOnMissingBean,…
- @Import: Nhập các cấu hình hoặc bean từ lớp khác.
- Ví dụ:
@Component
public class AppInfo {
@Value("${app.name}")
private String appName;
// Getter, Setter
}
@Configuration
@Profile("dev")
public class DevConfig {
// Các cấu hình chỉ dành cho môi trường development
}
Kết Luận
Spring Boot cung cấp một bộ sưu tập phong phú các annotation nhằm mục đích:
- Cấu hình và tự động cấu hình ứng dụng.
- Quản lý các bean và tiến trình Dependency Injection.
- Xây dựng các ứng dụng web RESTful cũng như ứng dụng MVC truyền thống.
- Tích hợp các cơ chế giao dịch, caching, lập lịch, và bảo mật.
- Hỗ trợ phát triển và kiểm thử ứng dụng một cách dễ dàng.
Việc hiểu rõ và sử dụng đúng các annotation sẽ giúp bạn thiết kế ứng dụng một cách module hoá, dễ bảo trì và tận dụng tối đa các tiện ích mà Spring Boot cung cấp.
Hy vọng bài viết trên sẽ là tài liệu tham khảo hữu ích cho bạn khi làm việc với Spring Boot!