The 30 second answer
@ComponentScan finds application components in the packages I tell it to scan. @SpringBootApplication is the broader shortcut: it combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. Its scan also includes filters that keep auto-configurations out of ordinary component scanning and support test slices. By default, scanning starts in the annotated class's package and includes its subpackages, which is why I put the main class above the application's other packages.
Here is the actual declaration:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {SpringBootApplication.java L42-L46
Each part has a job:
- **
@SpringBootConfiguration**: a@Configurationthat marks the main configuration. Spring Boot's test support uses it to find your configuration automatically with@SpringBootTest. An application should have only one. - **
@EnableAutoConfiguration**: imports auto-configuration candidates and records the base package with@AutoConfigurationPackage. JPA entity scanning and Spring Data repositories use that package by default. - **
@ComponentScan**: finds your@Component,@Service,@Repository,@Controllerand@Configurationclasses.
The two filters matter:
AutoConfigurationExcludeFilterstops component scanning from picking up auto-configuration classes as if they were normal configuration. They must come only through the auto-configuration path, so ordering and conditions apply.TypeExcludeFilterlets tests exclude types, for example in test slices like@WebMvcTest.
Why package location matters:
com.shop.App <- @SpringBootApplication here
com.shop.orders.OrderService scanned
com.other.Helper NOT scannedIf the main class is in com.shop.web, then com.shop.orders is not scanned, and you get NoSuchBeanDefinitionException at startup.
Using them separately is allowed. You can write @SpringBootConfiguration, @EnableAutoConfiguration and your own @ComponentScan("com.shop") instead, for example to scan a different package. @SpringBootApplication also exposes aliases such as scanBasePackages, exclude and proxyBeanMethods.
Sources (2)
- Spring Boot reference: Using the @SpringBootApplication annotationdocs.spring.io
- Spring Boot reference: Structuring your codedocs.spring.io