Sobes.tech
Junior — Middle

What are the differences between the @Service and @Repository annotations in the Spring Framework?

sobes.tech AI

Answer from AI

Annotations @Service and @Repository in the Spring Framework are both specialized component stereotypes, but they have different semantic meanings and additional functions:

  • @Service

    • Indicates a class as a service layer — business logic of the application.
    • Used for logic not directly related to data access.
    • Mainly serves for architectural clarity and automatic component scanning.
  • @Repository

    • Indicates a class as a data access component (DAO).
    • Besides marking, Spring applies exception handling to such classes, translating low-level database exceptions into unified Spring DataAccessException exceptions.
    • Helps in ORM integration and transaction management.

Thus, @Repository adds an additional error handling layer and data access semantics, while @Service is simply a service layer without additional exception handling logic.