How does ComponentScan work?
@ComponentScan
will give you a list of all annotated classes @Component
in the package (or @Service
/ @Repository
). For this, I am assuming they are using reflection to list all the classes in the package and find those that have this annotation.
However, according to this StackOverflow question, you cannot reliably list all the classes in a package because of the way it works ClassLoader
. So how @ComponentScan
does it seem to handle this?
source to share
@ComponentScan
works differently. A workflow will be listed shortly:
- Find all .class files in one folder and all subfolders
- Read the .class file and wrap it in an object
Resource
- Check to see if the class has annotations that make it a good candidate.
- If the class is a good candidate, create a bean from it.
Classes from Spring source code:
-
ComponentScanAnnotationParser
-
AnnotationConfigUtils
-
ClassPathBeanDefinitionScanner
-
BeanDefinitionReaderUtils
-
DefaultListableBeanFactory
source to share