Spring has many annotations used for different purposes. There are some key class annotations like @RestController @Controller, @Component, @Repository & @Service which do a similar job but actually have some differences between them and all extends @Component.
In General, you can think of these annotations used for the different domains in domain-driven design as given below
Annotation | Meaning |
---|---|
@Component | the generic stereotype for any Spring-managed component |
@Repository | the stereotype for the persistence layer |
@Service | the stereotype for the service layer |
@Controller | the stereotype for the presentation layer (spring-mvc) |
Here is the relationship between them
@Component
Indicates that an annotated class is a “component”. Such classes are considered candidates for auto-detection when using annotation-based configuration and classpath scanning.
Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the @Repository annotation or AspectJ’s @Aspect annotation.
@Repository
Indicates that an annotated class is a “Repository”, originally defined by Domain-Driven Design (Evans, 2003) as “a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects”..
A class thus annotated is eligible for Spring
DataAccessException
translation when used in conjunction with aPersistenceExceptionTranslationPostProcessor
. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc
@Service
Indicates that an annotated class is a “Service”, originally defined by Domain-Driven Design (Evans, 2003) as “an operation offered as an interface that stands alone in the model, with no encapsulated state.”
This annotation serves as a specialization of
@Component
, allowing for implementation classes to be autodetected through classpath scanning.
@Controller
Indicates that an annotated class is a “Controller” (e.g. a web controller).
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation.