What are the advantages of using @Repository and @Service?
Don't tell me about component scanning etc., I am looking forward to something extra benefits or features that are there if at all.
what happens if I don't use it? what is that I would be missing?
@Component is a generic stereotype for any Spring-managed component. @Service annotates classes at the service layer. @Repository annotates classes at the persistence layer, which will act as a database repository.
@Component is a generic stereotype for any Spring-managed component or bean. @Repository is a stereotype for the persistence layer. @Service is a stereotype for the service layer. @Controller is a stereotype for the presentation layer (spring-MVC).
Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.
There are no problem occur when I interchange the @service and @repository annotation in the spring MVC.
There are a few reasons:
@Repository
annotation carries with it some additional functionality: it causes exceptions to be wrapped up as DataAccessException
s.@Service
annotation may gain additional semantics in the future but it's not happened yet…The @Repository
annotation (introduced in Spring 2.0) and @Service
annotation (introduced in Spring 2.5) are specialization of the @Component
annotation.
The main advantage of using @Repository
or @Service
over @Component
is that it's easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository
.
Also, the specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With