13 tháng 7, 2026
3 phút đọcGiải thích chi tiết các annotation cốt lõi trong Spring Boot: @Component, @Service, @Repository, @Controller, @RestController, @Configuration, @Bean. Hiểu rõ sự khác biệt và khi nào sử dụng từng loại.

Spring sử dụng các annotation để đánh dấu class, giúp framework tự động phát hiện và quản lý chúng như các Bean trong IoC Container.
@Component là annotation gốc@Service, @Repository, @Controller đều kế thừa từ @Component@RestController kế thừa từ @ControllerAnnotation cơ bản nhất, đánh dấu một class là Spring Bean. Các annotation khác đều kế thừa từ @Component.
Khi nào dùng: Khi class không thuộc các layer cụ thể (Service, Repository, Controller).
1@Component
2public class EmailValidator {
3
4 public boolean isValid(String email) {
5 return email != null && email.matches("^[A-Za-z0-9+_.-]+@(.+)$");
6 }
7}Đánh dấu class chứa business logic. Về bản chất giống @Component nhưng mang ý nghĩa semantic rõ ràng hơn.
Khi nào dùng: Cho các class xử lý nghiệp vụ trong Service Layer.
1@Service
2public class OrderService {
3
4 private final OrderRepository orderRepository;
5
6 public OrderService(OrderRepository orderRepository) {
7 this.orderRepository = orderRepository;
8 }
9
10 @Transactional
11 public Order createOrder(CreateOrderRequest request) {
12 Order order = Order.builder()
13 .productId(request.getProductId())
14 .quantity(request.getQuantity())
15 .status(OrderStatus.PENDING)
16 .build();
17 return orderRepository.save(order);
18 }
19}Đánh dấu class truy cập database. Ngoài chức năng như @Component, nó còn tự động translate các database exception thành Spring DataAccessException.
Khi nào dùng: Cho các class trong Repository/DAO Layer.
1@Repository
2public interface UserRepository extends JpaRepository<User, Long> {
3
4 Optional<User> findByEmail(String email);
5
6 @Query("SELECT u FROM User u WHERE u.status = :status")
7 List<User> findByStatus(@Param("status") UserStatus status);
8}Đánh dấu class xử lý HTTP request trong Spring MVC, thường dùng với View (trả về HTML).
Khi nào dùng: Khi cần trả về View (Thymeleaf, JSP).
1@Controller
2@RequestMapping("/web")
3public class WebController {
4
5 @GetMapping("/users")
6 public String listUsers(Model model) {
7 model.addAttribute("users", userService.findAll());
8 return "users/list"; // Trả về view: templates/users/list.html
9 }
10}Kết hợp @Controller + @ResponseBody. Mọi method tự động trả về JSON/XML thay vì View.
Khi nào dùng: Khi xây dựng REST API.
1// @RestController = @Controller + @ResponseBody
2@RestController
3@RequestMapping("/api/v1/products")
4public class ProductController {
5
6 private final ProductService productService;
7
8 @GetMapping("/{id}")
9 public ResponseEntity<ProductResponse> getById(@PathVariable Long id) {
10 return ResponseEntity.ok(productService.findById(id));
11 }
12
13 @PostMapping
14 public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) {
15 return ResponseEntity.status(HttpStatus.CREATED).body(productService.create(request));
16 }
17}Đánh dấu class chứa các định nghĩa Bean. Thay thế cho file XML configuration.
Khi nào dùng: Khi cần cấu hình Bean thủ công, cấu hình third-party library.
1@Configuration
2public class AppConfig {
3
4 @Bean
5 public PasswordEncoder passwordEncoder() {
6 return new BCryptPasswordEncoder();
7 }
8
9 @Bean
10 public ObjectMapper objectMapper() {
11 ObjectMapper mapper = new ObjectMapper();
12 mapper.registerModule(new JavaTimeModule());
13 return mapper;
14 }
15}Đánh dấu method trong @Configuration class, method này trả về một Bean được Spring quản lý.
Khi nào dùng: Khi cần tạo Bean từ third-party class hoặc cần custom logic khởi tạo.
1@Configuration
2public class DataSourceConfig {
3
4 @Bean
5 @Primary
6 public DataSource dataSource() {
7 HikariDataSource ds = new HikariDataSource();
8 ds.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
9 ds.setUsername("root");
10 ds.setMaximumPoolSize(10);
11 return ds;
12 }
13}| Annotation | Kế thừa từ | Layer | Mục đích |
|---|---|---|---|
@Component | - | General | Bean tổng quát |
@Service | @Component | Service | Business logic |
@Repository | @Component | Repository | Data access, exception translation |
@Controller | @Component | Web | MVC controller, trả về View |
@RestController | @Controller | Web | REST API, trả về JSON |
@Configuration | @Component | Config | Định nghĩa Bean |
@Bean | - | Config | Tạo Bean trong @Configuration |
| @Component | @Bean |
|---|---|
| Đánh dấu trên class | Đánh dấu trên method |
| Spring tự tạo instance | Developer kiểm soát việc tạo instance |
| Dùng cho class của mình | Dùng cho third-party class |
1// @Component - class của mình
2@Component
3public class MyService { }
4
5// @Bean - third-party class
6@Configuration
7public class AppConfig {
8 @Bean
9 public RestTemplate restTemplate() {
10 return new RestTemplate();
11 }
12}@Component chỉ dùng khi class không thuộc layer nào@Bean dùng khi cần kiểm soát việc khởi tạo hoặc với third-party class