Senior
What is the difference between @Repository and @Component annotations in Spring?
sobes.tech AI
Answer from AI
The @Component annotation is a basic stereotype annotation in Spring that indicates that a class is a component and should be registered in the Spring context as a bean.
@Repository is a specialized annotation that extends @Component and is intended to denote the data access layer (DAO). It adds additional semantics and can influence exception handling, for example, converting database-specific exceptions into Spring DataAccessException.
In summary:
- @Component — a general component.
- @Repository — a data access layer component with additional exception handling.
Example:
@Repository
public class UserRepository {
// database access methods
}
@Component
public class UserService {
// business logic
}