Cả 4 đều là stereotype annotation — kích hoạt component scanning, tạo bean trong Spring container. Về mặt kỹ thuật gần như tương đương, nhưng mang ngữ nghĩa khác để code self-documenting.
| Annotation | Layer | Đặc biệt |
|---|---|---|
@Component | Generic | Đánh dấu bất kỳ class nào là Spring bean |
@Service | Business logic | Không thêm hành vi, chỉ semantic |
@Repository | Data access | Tự translate exception DB → DataAccessException |
@Controller | Web (Spring MVC) | Method bên trong có thể trả view name (template) |
@RestController | REST API | @Controller + @ResponseBody — trả JSON/XML thẳng |
@RestController
@RequiredArgsConstructor
class UserController {
private final UserService service; // inject
}
@Service
class UserService {
private final UserRepository repo;
}
@Repository
interface UserRepository extends JpaRepository<User, Long> {}Quy tắc: dùng đúng annotation theo layer — vi phạm (vd @Controller cho service) sẽ chạy được nhưng làm rối kiến trúc và miss @Repository-only translation.
All four are stereotype annotations — they enable component scanning and create beans in the Spring container. Technically nearly equivalent, but they carry different semantics for self-documenting code.
| Annotation | Layer | Notable |
|---|---|---|
@Component | Generic | Marks any class as a Spring bean |
@Service | Business logic | Adds no behaviour, just semantics |
@Repository | Data access | Auto translates DB exceptions → DataAccessException |
@Controller | Web (Spring MVC) | Methods may return view names (templates) |
@RestController | REST API | @Controller + @ResponseBody — returns JSON/XML directly |
@RestController
@RequiredArgsConstructor
class UserController {
private final UserService service; // injected
}
@Service
class UserService {
private final UserRepository repo;
}
@Repository
interface UserRepository extends JpaRepository<User, Long> {}Rule: use the right annotation per layer — misuse (e.g. @Controller on a service) still works but muddles architecture and loses @Repository-only exception translation.