Learnitweb

Difference Between @Component, @Service, and @Repository

1. Introduction

In the Spring Framework, all three annotations — @Component, @Service, and @Repository — are used to declare classes as Spring-managed beans.

This means:

  • Spring will automatically detect these classes during component scanning.
  • It will create their instances and manage their lifecycle in the ApplicationContext.

However, each annotation serves a different semantic role within a typical layered architecture.
Even though all of them ultimately act as components, they differ in meaning, intent, and sometimes behavior.

2. The Common Base: @Component

Definition

@Component is the base annotation from which other stereotype annotations derive.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
    String value() default "";
}

When a class is annotated with @Component, Spring considers it as a candidate for dependency injection and automatically creates an instance of it during startup.

Purpose

  • It is used for generic components that do not clearly belong to a specific layer (like service or repository).
  • Ideal for utility classes, helper components, custom annotations, and infrastructure beans.

Example

@Component
public class DateFormatter {
    public String formatDate(LocalDate date) {
        return date.toString();
    }
}

Key Idea

@Component = “This is a Spring-managed bean, but it doesn’t belong to any specific architectural layer.”

3. @Service Annotation

Definition

@Service is a specialization of @Component. It is meta-annotated with @Component, which means it inherits its functionality.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    String value() default "";
}

Purpose

  • Used to mark classes that contain business logic or service-layer operations.
  • Provides semantic clarity — helps communicate that this class performs core processing in the application.

Typical Layer

Service Layer — This is where business rules, validation, and orchestration logic reside.

Example

@Service
public class PaymentService {
    public void processPayment(String userId, double amount) {
        // Business logic for payment
    }
}

Benefits Over @Component

  1. Semantic Meaning – Other developers can immediately tell that the class contains business logic.
  2. AOP Targeting – You can write aspects (like logging or transaction management) that specifically apply to all @Service classes.
  3. Layer Clarity – It maintains the architectural separation between the controller, service, and repository layers.

4. @Repository Annotation

Definition

@Repository is another specialization of @Component.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    String value() default "";
}

Purpose

  • Used to mark classes that handle persistence logic — typically interacting with the database.
  • Indicates that the class belongs to the Data Access Layer.

Special Behavior

Unlike @Service, @Repository does more than just mark the layer. It also enables automatic exception translation.

Exception Translation

Spring automatically catches low-level persistence exceptions (e.g., SQLException, HibernateException) and rethrows them as Spring’s DataAccessException hierarchy.

This happens through the PersistenceExceptionTranslationPostProcessor, which recognizes classes annotated with @Repository.

So, this is the only stereotype annotation that adds special runtime behavior beyond marking a component.

Example

@Repository
public class UserRepository {

    public User findById(int id) {
        // Database access logic
        return new User(id, "Samir");
    }
}

If an exception occurs in the above method (like a SQLException), Spring can wrap it into a DataAccessException when @Repository is used — providing consistent error handling across persistence technologies.

5. Comparison Summary

Feature@Component@Service@Repository
PurposeGeneric component (no specific role)Represents the service layer (business logic)Represents the data access layer (database logic)
Meta-AnnotationBase stereotypeMeta-annotated with @ComponentMeta-annotated with @Component
BehaviorMarks as bean onlyMarks as bean (no extra behavior)Marks as bean + enables exception translation
Layer in ArchitectureAny general-purpose or utility layerBusiness/service layerPersistence/data access layer
Example Use CaseUtility class, helperBusiness logic classDAO class or JPA repository
Added ValueNone (generic)Semantic clarity + easier AOP targetingSemantic clarity + automatic exception translation
Best PracticeUse for shared utilitiesUse for business logicUse for persistence logic

6. Example: All Together

Let’s see how these annotations work in a typical Spring Boot application.

// Controller Layer
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable int id) {
        return userService.getUserDetails(id);
    }
}

// Service Layer
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User getUserDetails(int id) {
        // Some business logic (e.g., validation)
        return userRepository.findById(id);
    }
}

// Repository Layer
@Repository
public class UserRepository {

    public User findById(int id) {
        // Simulate DB call
        if (id < 0) {
            throw new RuntimeException("Invalid ID");
        }
        return new User(id, "Samir");
    }
}

Here:

  • UserController handles HTTP requests (uses @RestController).
  • UserService handles business rules (uses @Service).
  • UserRepository handles database operations (uses @Repository).

If the findById() method throws a database-related exception, Spring’s @Repository annotation ensures it gets translated into a DataAccessException, providing a consistent exception model.

7. Architectural Visualization

Textual representation of the layered structure:

+---------------------------------------------+
|                 Controller Layer            |
|     @Controller / @RestController           |
|     - Handles HTTP requests/responses       |
+---------------------------------------------+
                     |
                     v
+---------------------------------------------+
|                 Service Layer               |
|                 @Service                    |
|     - Contains business logic               |
|     - Interacts with multiple repositories  |
|     - May include transaction management    |
+---------------------------------------------+
                     |
                     v
+---------------------------------------------+
|               Repository Layer              |
|                @Repository                  |
|     - Interacts with the database           |
|     - Performs CRUD operations              |
|     - Provides exception translation        |
+---------------------------------------------+

8. Best Practices

  1. Follow the layered architecture strictly:
    • Use @Controller or @RestController for the web layer.
    • Use @Service for the business layer.
    • Use @Repository for the persistence layer.
    • Use @Component for utilities and infrastructure beans.
  2. Maintain semantic clarity — It helps others understand your code quickly.
  3. Use @Repository only for DAO or persistence classes so that exception translation can work effectively.
  4. Never mix stereotypes — each annotation clearly indicates a specific layer responsibility.

9. Key Takeaways

  • All three annotations make a class a Spring-managed bean.
  • @Component is generic, while @Service and @Repository provide semantic specialization.
  • @Repository is the only one that adds extra functionality (automatic exception translation).
  • Use the appropriate stereotype to make your code clean, maintainable, and consistent with Spring’s layered architecture principles.