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: you annotate a class @Component
, it tells hibernate that it is a Bean.
@Repository: you annotate a class @Repository
, it tells hibernate it is a DAO class and treat it as DAO class. Means it makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException
.
@Service: This tells hibernate it is a Service class where you will have @Transactional
etc Service layer annotations so hibernate treats it as a Service component.
Plus @Service
is advance of @Component
. Assume the bean class name is CustomerService
, since you did not choose XML bean configuration way so you annotated the bean with @Component
to indicate it as a Bean. So while getting the bean object CustomerService cust = (CustomerService)context.getBean("customerService");
By default, Spring will lower case the first character of the component – from ‘CustomerService’ to ‘customerService’. And you can retrieve this component with name ‘customerService’.
But if you use @Service
annotation for the bean class you can provide a specific bean name by
@Service("AAA")
public class CustomerService{
and you can get the bean object by
CustomerService cust = (CustomerService)context.getBean("AAA");