Junior — Middle
What is the purpose of the @Component annotation in Spring?
sobes.tech AI
Answer from AI
The @Component annotation in Spring is used to mark a class as a component that should be automatically detected and registered in the Spring context as a bean. This allows Spring to manage the lifecycle of the object, inject dependencies, and use it in other parts of the application.
Example:
@Component
public class UserService {
// business logic
}
When Spring scans the classes, it will find this class and create an instance of it, which can be injected via @Autowired.
Thus, @Component serves as a basic annotation for creating managed Spring components.