What's the difference between @Component, @Repository & @Service annotations in Spring?

 

In Spring Framework, @Component, @Repository, and @Service are all stereotype annotations used to define Spring beans, which are objects managed by the Spring container. While they are similar in that they all indicate that a class should be managed as a Spring bean, they have different intended use cases and carry some semantic differences:

  1. @Component:
    • @Component is a generic stereotype annotation that can be used to annotate any class as a Spring bean.
    • It is a common choice when you want to create a bean that doesn't fall into the more specific categories like @Repository or @Service.
java
@Component public class MyComponent { // ... }
  1. @Repository:
    • @Repository is a specialization of @Component that is typically used to indicate that a class fulfills the role of a data repository or data access object (DAO). It often works with databases and provides exception translation for database-specific exceptions.
    • Spring provides additional features, such as automatic translation of exceptions (e.g., SQLException) into a more Spring-friendly format.
java
@Repository public class UserRepository { // ... }
  1. @Service:
    • @Service is also a specialization of @Component and is used to annotate classes that provide business logic or services. It is often used in the service layer of a Spring application.
    • It is intended for service classes that contain business logic, and it's a way to better convey the purpose of the annotated class.
java
@Service public class UserService { // ... }

Here's a simple example demonstrating the use of these annotations in a Spring application:

java
@Component public class MyComponent { public void doSomething() { System.out.println("MyComponent is doing something."); } } @Repository public class UserRepository { public void saveUser(User user) { // Save user to the database } } @Service public class UserService { @Autowired private UserRepository userRepository; public void registerUser(User user) { userRepository.saveUser(user); System.out.println("User registered successfully."); } }

In this example:

  • MyComponent is annotated with @Component and can be used as a general Spring bean.
  • UserRepository is annotated with @Repository and is intended for data access operations.
  • UserService is annotated with @Service and represents a service class that uses the repository to provide business logic.

Spring's component scanning mechanism will automatically detect classes annotated with these stereotypes and create beans in the Spring application context. You can then inject these beans into other components and use them throughout your Spring application.

Comments