What is the difference between @Component, @Repository, @Service, and @Controller annotations in Spring?

Prasad Thilakarathne
2 min readJul 4, 2020

@Repository, @Service, and @Controller are extended from @Component. Which means technically all are the same. But there are some differences in usages and functionalities.

@Repository, @Service, and @Controller are extended from @Component

What is the similarity between these?

All of them allow Spring to detect them as Spring-managed Beans. It is called as component-scanning. We can define what is the package that contains the beans and Spring scan all the classes annotated with @Component.

@Component is a general-purpose stereotype annotation that indicates that it is a Spring-managed bean. Since @Service, @Repository, and @Controller are also annotated with @Component, those are also scanned.

What are the specialties of @Service, @Repository and @Controller?

Generally, these annotation represents the layers of the application.

@Service — is for service layer(Business logic)

@Repository — is for data access layer(Persistent layer)

@Controller — is for presentation layer(API layer)

Layers of an application

What are the specialties of @Controller?

@Controller annotation indicates that it is in the Presentation/API layer and serves as a controller. These classes receive requests from clients. First, the request receives by the Dispatcher servlet and it routes to the particular Controller by using the value of @RequestMapping annotation. You can only use @RequestMapping annotation on @Controller annotated classes.

What is @RestController annotation?

@RestController is again a specialized version of @Controller and it adds @Controller and @ResponseBody annotation automatically.

This annotation is very useful when creating RESTful web services using Spring MVC. It converts responses to JSON or XML.

What are the specialties of @Repository?

@Repository annotation indicates that the class is in DAO/Persistent/Data access layer. The main specialty on @Respository annotation over other annotations is it supports automatic exception translation. Exception translation means converting low-level exceptions into high-level Spring exceptions.

What are the specialties of @Service?

Apart from scanning and representing the layer which is the business logic happens, at the moment it does not provide any other functionality. Of cause you can call to database with a bean annotated with @Service annotation but better to strict to the convention as Spring may introduce some feature in future releases.

Conclusion

Difference between @Component, @Repository, @Service, and @Controller annotations in Spring

--

--