Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?>
Spring provides four different types of auto component scan annotations, they are @Component
, @Service
, @Repository
and @Controller
. Technically, there is no difference between them, but every auto component scan annotation should be used for a special purpose and within the defined layer.
@Component
: It is a basic auto component scan annotation, it indicates annotated class is an auto scan component.
@Controller
: Annotated class indicates that it is a controller component, and mainly used at the presentation layer.
@Service
: It indicates annotated class is a Service component in the business layer.
@Repository
: You need to use this annotation within the persistence layer, this acts like database repository.
One should choose a more specialised form of @Component
while annotating their class as this annotation may contain specific behavior going forward.