@Component in Spring: What It Is and How It Works
@Component is an annotation that marks a class as a Spring-managed bean. It tells Spring to automatically detect and create an instance of the class during application startup for dependency injection.How It Works
The @Component annotation works like a label that you put on a class to tell Spring, "Hey, please create an object of this class and manage it for me." Imagine you have a team where each member has a specific role. By marking a class with @Component, you are assigning it a role in the team that Spring will recognize and keep track of.
During the application startup, Spring scans the code for classes marked with @Component (and related annotations). It then creates objects (called beans) from these classes and keeps them ready to use. This process is called component scanning. Later, when another part of your program needs one of these objects, Spring can inject it automatically, so you don’t have to create it manually.
Example
This example shows a simple Spring component class and how Spring creates and uses it automatically.
import org.springframework.stereotype.Component; @Component public class GreetingService { public String greet() { return "Hello, Spring!"; } } import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyApp { private final GreetingService greetingService; @Autowired public MyApp(GreetingService greetingService) { this.greetingService = greetingService; } public void run() { System.out.println(greetingService.greet()); } } // In a Spring Boot application, MyApp would be run by the framework, which injects GreetingService automatically.
When to Use
Use @Component when you want Spring to manage a class as a bean but the class does not fit into more specific stereotypes like @Service, @Repository, or @Controller. It is a general-purpose annotation for any Spring-managed component.
For example, if you have utility classes, helper classes, or any custom components that need to be injected into other parts of your application, marking them with @Component lets Spring handle their lifecycle and dependencies automatically.
Key Points
- @Component marks a class as a Spring bean for automatic detection.
- Spring creates and manages the bean during application startup.
- It enables dependency injection without manual object creation.
- Use it for general-purpose beans that don’t fit other stereotypes.
- Works with Spring’s component scanning feature.
Key Takeaways
@Component tells Spring to create and manage an object of the class automatically.@Component for general beans that don’t fit specialized roles like services or controllers.@Component classes during component scanning at startup.