12

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

David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
  • 2
    With the help of [ClassPathScanningCandidateComponentProvider](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.html) – harshavmb Jun 07 '17 at 05:14
  • 1
    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! – harshavmb Jun 07 '17 at 05:23
  • @harshavmb, if you turn your comment into an answer, I'll upvote it. – Noel Yap May 28 '20 at 04:23
  • @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! – harshavmb May 28 '20 at 09:31

1 Answers1

8

@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
almirp
  • 81
  • 2