Java and Spring Level 1 This level · 74 of 105
Easy java spring

Difference between @ComponentScan and @SpringBootApplication?

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.

Could you say this in an interview?

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 @Configuration that 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, @Controller and @Configuration classes.

The two filters matter:

  • AutoConfigurationExcludeFilter stops 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.
  • TypeExcludeFilter lets 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 scanned

If 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)
  1. Spring Boot reference: Using the @SpringBootApplication annotationdocs.spring.io
  2. Spring Boot reference: Structuring your codedocs.spring.io
Previous
Next