Member-only story
Spring @Component
vs @Bean
vs @Service
vs @Repository
Explained
If you’re building applications using the Spring Framework, you’ve likely come across annotations like @Component
, @Service
, @Repository
, and @Bean
.
At first glance, they all seem to register a class or method as a Spring-managed bean. So, what’s the difference? And when should you use which one?
Let’s break it down in simple words — with examples, real-world scenarios, and a clear comparison table.
The main stereotype annotation is @Component. By using this annotation, Spring provides more Stereotype meta-annotations such as @Service, @Repository, and @Controller.
@Service annotation is used to create Spring beans at the Service layer.
@Repository is used to create Spring beans for the repositories at the DAO layer.
@Controller is used to create Spring beans at the controller layer.
Before diving deep into the concept, let’s first understand what a bean is in Spring.
What Is a Bean in Spring?
A bean is any object that is managed by the Spring container. Whether you define it in XML, Java config, or using annotations — as long as Spring creates and manages the lifecycle of that object, it’s a bean.