What will happen if we interchange @service and @repository annotation in the spring MVC
According to documentaion @Repository
,@Service
,@Controller
are all synonyms. They all just specializations of @Component
annotation. So, generally, they can be used one istead of other. But ... you should not do this.
First reason: any of this annotations make clear the role of your component in the application. Shows - is this component belongs to controller, service, or data layer.
Second reason: some of this 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 annotaion. Spring also will apply automatic exception translation to such classes. Another example, Spring Web MVC
process @Controller
, and use classes marked with it in URL mappings.
Actually, in future versions, some modules of Spring could process @Service
in 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.
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.