@Component is a stereotype annotation used to tell Spring that a class should be managed as a bean.
When Spring scans the classpath, it detects @Component classes and registers them inside the application context.
This is one of the simplest ways to create Spring-managed objects without writing explicit XML or @Bean methods.
@Component marks a class as a generic Spring bean.
In simple words:
“Spring, create an object of this class and manage its lifecycle.”
Spring can then inject that bean into other classes using @Autowired.
@Component
public class Engine {
public void start() {
System.out.println("Engine started");
}
}@Component
public class Car {
private final Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
}If component scanning is enabled, Spring creates both beans automatically.
@Component works only when Spring is told to scan the package.
@Configuration
@ComponentScan("com.example")
public class AppConfig {
}Spring Boot usually enables component scanning automatically through @SpringBootApplication.
@Component is the base annotation for other specialized annotations.
These annotations are built on top of it:
@Service@Repository@Controller
They all register beans, but each one expresses a different application role.
Used on the class itself.
@Component
public class Engine {
}Used on a method inside a @Configuration class.
@Bean
public Engine engine() {
return new Engine();
}@Componentis discovered automatically@Beanis declared explicitly
Use @Component when:
- the class is a regular application component
- the object should be discovered automatically
- you want less configuration
- there is no need for special semantic meaning like service or repository
By default, Spring creates a bean name from the class name.
@Component
public class EmailSender {
}Default bean name:
emailSender
You can also specify a custom name:
@Component("mailSender")
public class EmailSender {
}By default, a @Component bean is a singleton.
That means Spring creates one instance for the application context unless another scope is configured.
Example:
@Component
@Scope("prototype")
public class TaskProcessor {
}-
forgetting to enable component scanning
-
placing components outside the scanned package
-
using
@Componentwhen a more specific stereotype would be clearer -
assuming
@Componentautomatically makes a class a service or repository -
mixing manual object creation with Spring-managed beans
It marks a class as a Spring-managed bean.
The process by which Spring searches for classes annotated with @Component and registers them.
@Component is class-based and discovered automatically, while @Bean is method-based and declared explicitly.
@Service, @Repository, and @Controller.
-
@Componentturns a class into a Spring bean -
It depends on component scanning
-
It is the base stereotype annotation in Spring
-
Prefer specific stereotypes when the class has a clear role
-
Default scope is singleton