With Spring’s auto-scanning feature, it automatically detects various beans defined in our application. We usually annotate our beans using one of the available Spring annotations – @Component, @Repository, @Service, @Controller.
On detecting the bean, Spring simply registers it into the ApplicationContext.
In this quick tutorial, we’ll look at the difference between @Component, @Repository, and, @Service Spring annotations.
We can use @Component annotation to mark a bean as a Spring-managed component. In other words, it’s a generic stereotype for any Spring-managed component.
We can enable an auto-scan using <context:component-scan> tag. During auto-scan, Spring will scan and register all beans marked with a @Component annotation:
@Component public class Employee { ... }
@Repository annotation is a specialization over @Component annotation:
@Component public @interface Repository { }
Since @Repository is a type of @Component, Spring also auto-scans and registers them.
@Repository is a stereotype for the persistence layer. Its job is to catch all persistence related exceptions and rethrow them as a Spring DataAccessException.
For this, we should configure PersistenceExceptionTranslationPostProcessor in our application context:
<bean class= "org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
This bean post processor adds an advisor to all beans marked with @Repository. The advisor’s responsibility is to translate the platform-specific exceptions to the Spring’s unified unchecked exceptions.
Just like @Repository, @Service is another specialization of @Component:
@Component public @interface Service { }
Just like @Repository, @Service is also a type of @Component. That means Spring will also automatically detect such beans.
The @Service annotation represents that our bean holds some business logic. Till date, it doesn’t provide any specific behavior over @Component.
Still, we should annotate the service-layer beans with the @Service annotation to make our intent clear. Additionally, we never know if someday Spring chooses to add some specific functionality to it.
Let’s quickly sum up the differences between @Component, @Repository and, @Service:
In this mini-tutorial, we have learned the difference between the popular Spring annotations – @Component, @Service, and @Repository.
To conclude, we should always prefer using the annotations based on their specific layer conventions.