Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if we interchange @service and @repository annotation in the spring MVC

Why we needs to use @service inside the service Implementation and @repository in the DAO Implementation. There are no problem occur when I interchange the @service and @repository annotation in the spring MVC.

like image 375
Hisoban Avatar asked Feb 17 '16 06:02

Hisoban


2 Answers

According to documentaion @Repository,@Service,@Controller are all synonyms. They all are just specializations of @Component annotation. So, generally, they can be used one instead of other. But ... you should not do this.

First reason: any of these annotations make clear the role of your component in the application. Shows - is this component belongs to the controller, service, or data layer.

Second reason: some of these annotations processed differently by different Spring modules. For example, Spring Data JPA will process @Repository and will try to replace with implementation any interface marked by this annotation. Spring also will apply automatic exception translation to such classes. Another example: Spring Web MVC processes @Controller, and uses classes marked with it in URL mappings.

Actually, in future versions, some modules of Spring could process @Service in a particular way. Not as simple @Component. That's why documentation advises:

It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice.

like image 181
Ken Bekov Avatar answered Oct 19 '22 22:10

Ken Bekov


It depends on what you use for the remainder of the framework. In theory nothing changes as the @Service and @Repository annotations are basically @Component annotations. The same could be said for @Controller or @Endpoint (for Spring Ws and there are more).

However they express an intent of what a class is (a service, a repository) and makes it clear to the user to what layer that class belongs.

However if you also use Spring for transaction managemnt then @Repository is also a trigger for adding exception translation to that class (also see the reference guide).

Although nothing has to break it probably will at some point.

like image 25
M. Deinum Avatar answered Oct 19 '22 22:10

M. Deinum