Difference between @Service and @Repository annotation in spring boot?
This is very popular interview question in spring boot .Here I have tried to explain how we can answer this question in interview .
To understand the difference we should know the purpose of @Component annotation in spring . This is a stereotype annotation. When we mark any bean with @Component annotation then spring picks that bean and register in ApplicationContext and that bean becomes spring managed bean. Now we can inject theses beans wherever we want in the application without writing any explicit code .
Now question comes if we have @Component annotation then what is the use of these @Service and @Repository annotations..
These @Service and @Repository annotations internally uses @Component annotation only for scanning and autodetecting the beans .Like in below picture you can see that the Service annotation is internally using Component annotation.
But if I talk about @Repository annotation , It does the same but it also helps us to achieve the exception translation feature so that Spring will wrap up any exception thrown by your persistence layer with a DataAccessException. As we can see in below picture ..
That is the only difference between between @service and @repository annotation so don’t get confuse when interviewer ask to differentiate between @service and @repository or between @controller and @repository. Thanks and happy learning .Stay connected for more such content.