Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

The @Component annotation in Spring is used to denote any component that should be registered as a Spring Bean. It is a general stereotype that can be applied to any class.

@Repository is a specialized stereotype that extends @Component and is intended for classes that work with the database (DAO layer). Besides registering the bean, @Repository adds exception handling related to data access, automatically translating low-level exceptions into Spring's DataAccessException.

Thus, the main difference:

  • @Component — a general component.
  • @Repository — a component for data access with additional semantics and exception handling.

Example:

@Repository
public class UserDao {
    // database access methods
}

@Component
public class UserService {
    // business logic
}
What is the difference between @Component and… - sobes.tech