Junior — Middle
What is the advantage of using the @Component annotation for a class in Spring?
sobes.tech AI
Answer from AI
The @Component annotation in Spring is used for automatic detection and registration of a class as a bean in the application context. It allows Spring to manage the lifecycle of the object, inject dependencies, and configure it without explicit XML or Java configuration.
Advantages of using @Component:
- Automatic registration: the class automatically becomes a bean if it is in a scanned package.
- Simplifies configuration: no need to declare the bean explicitly in configuration files.
- Integration with DI: Spring can inject dependencies into this class and use it in other components.
Example:
import org.springframework.stereotype.Component;
@Component
public class MyService {
public void doWork() {
System.out.println("Work done");
}
}
When the application starts, Spring creates an instance of MyService and can inject it into other beans via @Autowired. This facilitates modularity and testability.