I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Introduction

In this quick tutorial, we’re going to learn about the differences between @Component, @Repository, @Service annotations, in the Spring Framework.

2. Spring Annotations

In most typical applications, we have distinct layers like data access, presentation, service, business, etc.

And, in each layer, we have various beans. Simply put, to detect them automatically, Spring uses classpath scanning annotations.

Then, it registers each bean in the ApplicationContext.

Here’s a quick overview of a few of these annotations:

@Component is a generic stereotype for any Spring-managed component

@Service annotates classes at the service layer

@Repository annotates classes at the persistence layer, which will act as a database repository

We already have an extended article about these annotations. So we’ll keep the focus only on the differences between them.

3. What’s Different?

The major difference between these stereotypes is they are used for different classification. When we annotate a class for auto-detection, then we should use the respective stereotype.

Now, let’s go through them in more detail.

3.1. @Component

We can use @Component across the application to mark the beans as Spring’s managed components. Spring only pick up and registers beans with @Component and doesn’t look for @Service and @Repository in general.

They are registered in ApplicationContext because they themselves are annotated with @Component:

@Component
public @interface Service {
}

@Component
public @interface Repository {
}

@Service and @Repository are special cases of @Component. They are technically the same but we use them for the different purposes.

3.2. @Repository

@Repository’s job is to catch persistence specific exceptions and rethrow them as one of Spring’s unified unchecked exception.

For this Spring provides PersistenceExceptionTranslationPostProcessor, that requires to add in our application context: