Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

These are Spring annotations used to designate classes as components of specific layers of the application:

  • @Service: Used for classes representing business logic. Usually contains methods that process data received from the repository layer.
  • @Repository: Used for classes interacting with the data storage layer (e.g., a database). Provides methods for data access.
  • @Controller: Used for classes that handle incoming HTTP requests. Usually contains methods that return views or data in response to requests.

All these annotations are stereotype annotations that extend @Component, allowing Spring to automatically detect and register these classes as beans in the application context. Their main difference is semantic, indicating the role of the class in the architecture. Spring can use these annotations to apply layer-specific functions, for example:

  • Spring Data JPA automatically scans classes with @Repository to create repository implementations.
  • Spring MVC uses @Controller for mapping URL requests to controller methods.