Performance: @Component annotation
This affects application startup time and memory usage by controlling bean creation and dependency injection.
@Component
@Lazy
public class HeavyService {
public HeavyService() {
// expensive initialization
}
}@Component
public class HeavyService {
public HeavyService() {
// expensive initialization
}
}| Pattern | Bean Creation | Startup Delay | Memory Usage | Verdict |
|---|---|---|---|---|
| Eager @Component | Creates all beans at startup | High delay if many heavy beans | High memory usage | [X] Bad |
| @Component with @Lazy | Creates beans on demand | Minimal startup delay | Lower memory usage initially | [OK] Good |
@Component annotation in Spring Boot?@Component@Component annotation tells Spring to create an instance of the class and manage it automatically.@Component.@Component = automatic management [OK]@Component means Spring manages the class [OK]@Component with @Entity@Component annotation must be placed above a class declaration, like @Component public class MyService {}.@Service or @Component is invalid since components must be classes.@Component above a class, not a method [OK]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";
}
}App and ServiceA are annotated with @Component, so Spring creates and manages their instances. The @Autowired injects ServiceA into App.app.run() prints the result of serviceA.getName(), which returns "ServiceA".@Component
public class MyComponent {
@Autowired
private ServiceB serviceB;
public void doWork() {
serviceB.perform();
}
}ServiceB is not annotated with @Component or any stereotype, what will happen?@Component or similar. Since ServiceB lacks this, Spring won't create its bean.serviceB, it finds no bean and throws a runtime error (NoSuchBeanDefinitionException).PaymentService and have Spring inject the correct one based on a custom qualifier. How should you use @Component to achieve this?PaymentService must be annotated with @Component so Spring manages them.@Qualifier to distinguish@Qualifier with the component name to tell Spring which implementation to use.@Component and use @Qualifier to specify which to inject -> Option B@Component on all, @Qualifier to pick one [OK]@Qualifier when multiple beans existPass the test and this pattern moves unknown