What is the difference between @Component, @Repository, and @Service annotations in Spring, and what are their purposes?
sobes.tech AI
Answer from AI
In Spring, the annotations @Component, @Repository, and @Service serve to mark classes as components that will be automatically detected and registered in the Spring context (beans).
-
@Component — a basic universal annotation for any Spring component. Used when the class does not fit more specific roles.
-
@Repository — a specialized annotation for classes responsible for data access (DAO). Besides registering in the context, it helps Spring handle database-related exceptions by translating them into unified DataAccessException.
-
@Service — an annotation for the service layer, where business logic is implemented. It serves for semantic distinction and can be used for additional aspects, such as transactions.
Thus, all three annotations make a class a Spring bean, but they help structure the application and provide Spring with additional information for component processing.