Sobes.tech
Middle

What is the difference between the annotations Repository, Component, Controller, and Service in Spring?

sobes.tech AI

Answer from AI

These annotations are stereotype annotations for Spring components:

  • @Component: The basic annotation for any component managed by the Spring IoC container. It implies that the class is a general component of the application.
  • @Repository: A specialized annotation for classes that perform data operations (DAO). Spring provides additional capabilities, such as automatic translation of JDBC exceptions into Spring DataAccessException.
  • @Service: A specialized annotation for classes containing business logic. It indicates that the class is a service at the business logic level.
  • @Controller: A specialized annotation for classes used as controllers in the web layer. Usually used in Spring MVC to handle incoming web requests.

All these annotations are meta-annotations for @Component, meaning that a class annotated with any of them will be considered a component by Spring. The main difference lies in the semantics and the specialized functionality that Spring can provide for each.

// Example of using @Component
@Component
public class MyGenericComponent {
    // general functionality
}

// Example of using @Repository
@Repository
public class UserRepository {
    // database operations
}

// Example of using @Service
@Service
public class UserService {
    // business logic
}

// Example of using @Controller
@Controller
public class UserController {
    // handling web requests
}
What is the difference between the annotations… - sobes.tech