Framework/SPRING

Component Scanning

데먕 2020. 5. 23. 19:46

1. Overview

With Spring, we use the @ComponentScan annotation along with @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.

Note that the main application class is also a bean as it's annotated with @Configuration, which is a @Component.

Also, note that the main application class and the configuration class are not necessarily the same. If they are different, it doesn't matter where to put the main application class. Only the location of the configuration class matters as component scanning starts from its package by default.

2. @SpringBootApplication annotation

The trick with Spring Boot is that many things happen implicitly. We use the @SpringBootApplication annotation, but it's just a combination of three annotations:

@Configuration
@EnableAutoConfiguration
@ComponentScan

3. @ComponentScan With Arguments

3.1 @ComponentScan for Specific Packages

3.2 @ComponentScan with Exclusions

3. Default package

We should avoid putting the @Configuration class in the default package (i.e. by not specifying the package at all). In this case, Spring scans all the classes in all jars in a classpath. That causes errors and the application probably doesn't start.

3. Reference

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring