How does Spring determine that a class is a component for dependency injection?
sobes.tech AI
Answer from AI
Spring determines that a class is a component for dependency injection if this class is marked with a special annotation, such as @Component, @Service, @Repository, or @Controller. These annotations indicate to Spring that this class should be registered as a bean in the application context and managed by the Spring container.
Additionally, component scanning is used for automatic detection of such classes, which is configured via the @ComponentScan annotation or in configuration files. During scanning, Spring looks for classes with the specified annotations and creates their instances for dependency injection.
Example:
@Component
public class MyService {
// service logic
}
In this example, the MyService class will be automatically registered as a bean and available for injection into other components.