Sobes.tech
Middle

What is the difference between annotations @Component, @Repository, and @Service in Spring?

sobes.tech AI

Answer from AI

These annotations are Spring stereotypes used to mark application components. The difference lies in their semantic purpose and the functionality that Spring can add.

  • @Component: A general annotation for any Spring-managed component. Used for general-purpose classes.
  • @Repository: Applied to data access layer (DAO) classes. Spring can automatically translate specific data access exceptions (e.g., SQLException) into Spring exceptions (e.g., DataAccessException), simplifying error handling.
  • @Service: Used for service layer classes. Although it doesn't add special functionality compared to @Component, it helps in better code organization and explicitly indicates the component's role.

These annotations help Spring understand the application's structure and apply appropriate processing (e.g., transactions for @Repository or @Service).

Example usage:

// General component
@Component
public class GeneralComponent {
    // ...
}

// Data Access Object component
@Repository
public class UserRepository {
    // ...
}

// Service layer component
@Service
public class UserService {
    // ...
}