Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement