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.
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.
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.
According to documentation
Service.java
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Service { @AliasFor(annotation = Component.class) String value() default ""; }
Repository.java
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Repository { @AliasFor(annotation = Component.class) String value() default ""; }
So after reading documentation, it seems we don't get immediate error and theoretically is possible but it is not good practice.If in future Spring offically add new line of code then we may get error.
© 2022 - 2024 — McMap. All rights reserved.