Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?>
@Component
, @ Repository
, @ Service
, @Controller
:
@Component
is a generic stereotype for the components managed by Spring @Repository
, @Service
, and @Controller
are @Component
specializations for more specific uses:
@Repository
for persistence@Service
for services and transactions@Controller
for MVC controllersWhy use @Repository
, @Service
, @Controller
over @Component
?
We can mark our component classes with @Component, but if instead we use the alternative that adapts to the expected functionality. Our classes are better suited to the functionality expected in each particular case.
A class annotated with @Repository
has a better translation and readable error handling with org.springframework.dao.DataAccessException. Ideal for implementing components that access data (DataAccessObject or DAO).
An annotated class with @Controller
plays a controller role in a Spring Web MVC application
An annotated class with @Service
plays a role in business logic services, example Facade pattern for DAO Manager (Facade) and transaction handling