Sobes.tech
Junior — Middle

What is the difference between using @Service and @Repository annotations in Spring Framework?

sobes.tech AI

Answer from AI

Annotations @Service and @Repository in Spring Framework are both specialized stereotypes for components but have different semantic meanings and additional functions.

  • @Service is used to denote the service layer — business logic of the application. It indicates that the class contains business methods and serves for logical organization of code.

  • @Repository is used for the data access layer (DAO). Besides marking the class as a Spring component, it also provides automatic translation of database-related exceptions into Spring DataAccessException hierarchy.

Example:

@Service
public class UserService {
    // business logic
}

@Repository
public class UserRepository {
    // data access, e.g., via JPA
}

Thus, @Repository adds additional functionality for exception handling, while @Service is just a semantic marker for the business layer.

What is the difference between using @Service and… - sobes.tech