@ComponentScan will give you a list of all the classes with the @Component annotation in a package (or @Service/@Repository). To do this I imagine they use reflection to enumerate all the classes in a package and find the ones with that annotation.
However according to other StackOverflow answers you can not reliably enumerate all the classes in a package due to how the ClassLoaderworks. So how does @ComponentScan seemingly manage to accomplish this?
The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.
@Component and @ComponentScan are for different purposes. @Component indicates that a class might be a candidate for creating a bean. It's like putting a hand up. @ComponentScan is searching packages for Components.
Using @ComponentScan in a Spring Application. With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.
For example , it has an attribute called scanBasePackages which tells Spring to scan the beans (A class that is annotated with @Component or its sterotypes such as @Service , @Repository , @Controller etc. ) from certain packages and its sub-packages only.
@ComponentScan works differently. Workflow is put shortly this:
Resource objectClasses from Spring source code to look:
ComponentScanAnnotationParserAnnotationConfigUtilsClassPathBeanDefinitionScannerBeanDefinitionReaderUtilsDefaultListableBeanFactoryIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With