Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ComponentScan work?

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

like image 634
David says Reinstate Monica Avatar asked Jun 07 '17 04:06

David says Reinstate Monica


People also ask

What is the purpose of using @ComponentScan?

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.

What is difference between @component and @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.

How does Spring boot component scan work?

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.

How does Spring scan for beans?

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.


1 Answers

@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
like image 144
almirp Avatar answered Sep 21 '22 18:09

almirp