The @Component annotation tells Spring to create and manage an object automatically. It helps you avoid writing extra code to make objects yourself.
@Component annotation in Spring Boot
@Component public class MyClass { // class body }
Place @Component above the class declaration.
Spring will create one instance (singleton) by default.
@Component public class ServiceHelper { public void help() { System.out.println("Helping..."); } }
@Component("customName") public class CustomComponent { // class body }
This example shows two classes marked with @Component. Spring creates and connects them automatically. The UserController uses GreetingService to print a greeting.
import org.springframework.stereotype.Component; @Component public class GreetingService { public String greet(String name) { return "Hello, " + name + "!"; } } import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class UserController { private final GreetingService greetingService; @Autowired public UserController(GreetingService greetingService) { this.greetingService = greetingService; } public void sayHello() { System.out.println(greetingService.greet("Alice")); } } import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Application { public static void main(String[] args) { var context = new AnnotationConfigApplicationContext("your.package.name"); UserController userController = context.getBean(UserController.class); userController.sayHello(); context.close(); } }
Spring creates only one instance of a @Component class by default (singleton).
Use @Autowired to let Spring connect components automatically.
Make sure your package is scanned by Spring to find @Component classes.
@Component marks a class for Spring to manage automatically.
It helps connect parts of your app without manual object creation.
Use @Autowired to inject these components where needed.
Practice
@Component annotation in Spring Boot?Solution
Step 1: Understand the role of
The@Component@Componentannotation tells Spring to create an instance of the class and manage it automatically.Step 2: Compare with other options
The other options relate to other Spring features like entities, properties, or controllers, not@Component.Final Answer:
To mark a class so Spring automatically creates and manages its instance -> Option AQuick Check:
@Component= automatic management [OK]
@Component means Spring manages the class [OK]- Confusing
@Componentwith@Entity - Thinking it handles HTTP requests
- Assuming it configures properties
Solution
Step 1: Check annotation placement and class declaration
The@Componentannotation must be placed above a class declaration, like@Component public class MyService {}.Step 2: Identify incorrect syntax
A plain public class misses the annotation, annotating a method with@Serviceor@Componentis invalid since components must be classes.Final Answer:
@Component public class MyService {} -> Option AQuick Check:
Annotation + class declaration = correct syntax [OK]
@Component above a class, not a method [OK]- Annotating methods instead of classes
- Missing the annotation entirely
- Using wrong annotations for components
app.run() is called?@Component
public class App {
@Autowired
private ServiceA serviceA;
public void run() {
System.out.println(serviceA.getName());
}
}
@Component
public class ServiceA {
public String getName() {
return "ServiceA";
}
}Solution
Step 1: Understand component scanning and injection
BothAppandServiceAare annotated with@Component, so Spring creates and manages their instances. The@AutowiredinjectsServiceAintoApp.Step 2: Trace the method call
Callingapp.run()prints the result ofserviceA.getName(), which returns "ServiceA".Final Answer:
ServiceA -> Option CQuick Check:
Autowired injects component = output string [OK]
- Assuming serviceA is null without injection
- Confusing compilation vs runtime errors
- Forgetting to annotate both classes
@Component
public class MyComponent {
@Autowired
private ServiceB serviceB;
public void doWork() {
serviceB.perform();
}
}Assuming
ServiceB is not annotated with @Component or any stereotype, what will happen?Solution
Step 1: Check bean creation requirements
Spring only manages classes annotated with@Componentor similar. SinceServiceBlacks this, Spring won't create its bean.Step 2: Understand autowiring consequences
When Spring tries to injectserviceB, it finds no bean and throws a runtime error (NoSuchBeanDefinitionException).Final Answer:
Spring will throw a runtime error due to missing bean -> Option DQuick Check:
Missing @Component = runtime injection error [OK]
- Assuming Spring creates beans without annotation
- Confusing compile errors with runtime errors
- Forgetting to annotate dependencies
PaymentService and have Spring inject the correct one based on a custom qualifier. How should you use @Component to achieve this?Solution
Step 1: Annotate both implementations
Both classes implementingPaymentServicemust be annotated with@Componentso Spring manages them.Step 2: Use
When injecting, use@Qualifierto distinguish@Qualifierwith the component name to tell Spring which implementation to use.Final Answer:
Annotate both implementations with@Componentand use@Qualifierto specify which to inject -> Option BQuick Check:
Multiple components + qualifier = correct injection [OK]
@Component on all, @Qualifier to pick one [OK]- Annotating only one implementation
- Annotating interface instead of classes
- Not using
@Qualifierwhen multiple beans exist
Ready to prove it?
Pass the test and this pattern moves unknown
