Junior — Middle
How will the behavior of a class change when using the @Component annotation in Spring?
sobes.tech AI
Answer from AI
The @Component annotation in Spring indicates that the class is a Spring component and should be automatically detected and registered in the application context as a Spring Bean. This means that Spring will create an instance of this class and manage its lifecycle.
Without @Component, the class is a regular POJO, and Spring will not automatically create or inject it.
Example:
@Component
public class MyService {
public void doSomething() {
System.out.println("Service work");
}
}
Now, MyService can be injected into other components via @Autowired.
Thus, using @Component allows integrating the class into the Spring infrastructure, including dependency injection and lifecycle management.