Sobes.tech
Junior — Middle

What is the purpose of the @ComponentScan annotation in the context of automatic component registration in Spring?

sobes.tech AI

Answer from AI

The @ComponentScan annotation in Spring is used for automatic detection and registration of components (beans) in the application context. It tells Spring which packages to scan for classes annotated with @Component, @Service, @Repository, @Controller, etc.

When the application starts, Spring scans the specified packages and automatically creates instances of these classes and places them in the context, which facilitates dependency management and configuration.

Example of usage:

@Configuration
@ComponentScan(basePackages = "com.example.myapp.services")
public class AppConfig {
}

Here, Spring will scan the package com.example.myapp.services and register all components from it.