How does ComponentScan work?
Asked Answered
M

1

14

@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?

Michael answered 7/6, 2017 at 4:45 Comment(4)
With the help of ClassPathScanningCandidateComponentProviderUniformed
The above class has a method findCandidateComponents accepting basePackage as an input argument and then ResourcePatternResolver instance reads all the classpath files with .class suffix. Hope this helps!Uniformed
@harshavmb, if you turn your comment into an answer, I'll upvote it.Boswell
@NoelYap, so nice of you! I feel it's too late to put it as an answer that I almost forgot Java & Spring. Sorry to disappoint!Uniformed
A
11

@ComponentScan works differently. Workflow is put shortly this:

  • Find all .class files in same folder and all subfolders
  • Read .class file and wrap it into Resource object
  • Check if class has annotations that will make it good candidate
  • If class is good candidate, create bean from it.

Classes from Spring source code to look:

  • ComponentScanAnnotationParser
  • AnnotationConfigUtils
  • ClassPathBeanDefinitionScanner
  • BeanDefinitionReaderUtils
  • DefaultListableBeanFactory
Acapulco answered 7/6, 2017 at 6:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.