Junior
What does the scan component do in Java?
sobes.tech AI
Answer from AI
In the Spring Framework, <context:component-scan> is used in XML configuration for automatic discovery and registration of Spring components (such as @Component, @Service, @Repository, @Controller) in specified packages.
This eliminates the need to manually declare each bean in the XML file. Spring scans classes in the specified packages, finds annotated classes, and creates corresponding bean definitions in the application context.
Main attributes:
base-package: Specifies the packages where Spring should look for components. Multiple packages can be specified separated by commas or semicolons.
Example usage:
<context:component-scan base-package="com.example.package1, com.example.package2"/>
In Java-based configuration (using @Configuration):
// Java configuration uses the @ComponentScan annotation
@Configuration
@ComponentScan(basePackages = {"com.example.package1", "com.example.package2"})
public class AppConfig {
// ... bean definitions
}
The advantage of using component-scan is simplifying Spring application configuration and improving development convenience.