Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?
From Spring Documentation:
In Spring 2.0 and later, the
@Repositoryannotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. Among the uses of this marker is the automatic translation of exceptions.Spring 2.5 introduces further stereotype annotations:
@Component,@Service, and@Controller.@Componentis a generic stereotype for any Spring-managed component.@Repository,@Service, and@Controllerare specializations of@Componentfor more specific use cases, for example, in the persistence, service, and presentation layers, respectively.Therefore, you can annotate your component classes with
@Component, but by annotating them with@Repository,@Service, or@Controllerinstead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts.Thus, if you are choosing between using
@Componentor@Servicefor your service layer,@Serviceis clearly the better choice. Similarly, as stated above,@Repositoryis already supported as a marker for automatic exception translation in your persistence layer.
┌────────────┬─────────────────────────────────────────────────────┐
│ Annotation │ Meaning │
├────────────┼─────────────────────────────────────────────────────┤
│ @Component │ generic stereotype for any Spring-managed component │
│ @Repository│ stereotype for persistence layer │
│ @Service │ stereotype for service layer │
│ @Controller│ stereotype for presentation layer (spring-mvc) │
└────────────┴─────────────────────────────────────────────────────┘