When you're learning Spring Boot, you’ll often come across two important
annotations: @Bean
and @Component
.
Both are used to register Spring Beans – which are just Java objects that Spring manages for you. But when and why should you use one over the other?
Let’s simplify the confusion.
What is a Spring Bean?
In Spring Boot, a Bean is an object that is managed by the Spring IoC (Inversion of Control) container.
Whenever you want Spring to manage the lifecycle of an object (like creating, injecting dependencies, destroying), you declare it as a Bean.
@Component – Auto-detected Bean
@Component
is a class-level annotation.- It tells Spring "Hey, create an object of this class and manage it as a bean."
- It works automatically if your class is inside a package scanned by Spring.
✅ When to use @Component
?
Use it when you control the source code of the class.
✅ Example using @Component
@Component
public class MyService {
public void doSomething() {
System.out.println("Doing something...");
}
}
And use it in another class:
@RestController
public class MyController {
private final MyService myService;
public MyController(MyService myService) {
this.myService = myService;
}
@GetMapping("/test")
public String test() {
myService.doSomething();
return "Done";
}
}
@Bean – Manual Bean Declaration
@Bean
is a method-level annotation.-
You use it inside a
@Configuration
class to tell Spring:
"Call this method, get its return object, and register it as a bean." -
Useful when you
can’t or don’t want to use
@Component
(like for third-party classes).
✅ When to use @Bean
?
Use it when you don’t have access to the class source code (like third-party libraries).
✅ Example using @Bean
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
Now Spring will treat MyService
as a managed bean – even though
it wasn’t annotated with @Component
.
📊 Comparison Table
Feature | @Component | @Bean |
---|---|---|
Annotation Level | Class level | Method level |
Declaration Location | On the actual class | Inside a @Configuration class |
Discovery | Component scan (automatic) | Manual bean registration |
Use case | Own classes you can annotate | Third-party classes or special configuration |
Flexibility | Less flexible | More control (you can call constructors, pass params, etc.) |
📌 Summary
- Use @Component – when you own the code and want Spring to discover it automatically.
- Use @Bean – when you need more control or are using third-party classes.
Both are valid ways to define beans. Use whichever fits your use case best!
0 Comments