Sub topic 3
What @SpringBootApplication Really Enables
This chapter assumes you know what a bean and the application context are, and that you can write @Configuration classes with @Bean methods. You should also be able to run a simple Spring Boot application. You will look inside the one annotation that sits on almost every Boot main class and see what each of its parts does.
The annotation is a bundle
@SpringBootApplication is a meta-annotation. It carries three other annotations, so putting it on a class has the same effect as putting all three there.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}The annotation combines these:
| Annotation | What it does |
|---|---|
| `@SpringBootConfiguration` | Marks the class as a configuration class. It is a specialized `@Configuration`, so the class can declare `@Bean` methods. |
| `@EnableAutoConfiguration` | Turns on auto-configuration: Boot reads a list of candidate configuration classes and applies the ones whose conditions match. |
| `@ComponentScan` | Scans the package of the annotated class and its sub-packages for `@Component`, `@Service`, `@Repository`, `@Controller` and `@Configuration` classes. |
The explanation for the code above is simple: @SpringBootApplication combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan, and the second one is what switches auto-configuration on.
@SpringBootConfiguration
@SpringBootConfiguration is meta-annotated with @Configuration. The difference matters mostly for tests. Test support such as @SpringBootTest searches upward from the test's package until it finds a class annotated with @SpringBootConfiguration, and uses it as the configuration root. This is why a Boot application normally has exactly one such class. Two of them in the search path make the lookup ambiguous.
Because the class is a configuration class, you can also declare beans on it directly:
@SpringBootApplication
public class DemoApplication {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}This is fine for a few small beans. For larger applications, move beans into separate @Configuration classes so the main class stays readable.
@ComponentScan and the package rule
@ComponentScan with no arguments scans the package of the class that carries it. That is the single most common source of "my bean is not found" errors in new projects.
Suppose the main class is com.example.shop.ShopApplication. These classes are found:
com.example.shop.OrderServicecom.example.shop.web.OrderControllercom.example.shop.persistence.OrderRepository
This one is not found:
com.example.billing.InvoiceService
The usual fix is to move the main class to a root package above everything else. You can instead widen the scan with scanBasePackages:
@SpringBootApplication(scanBasePackages = {"com.example.shop", "com.example.billing"})
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}Component scanning has a built-in guard that keeps it from picking up auto-configuration classes by accident. @SpringBootApplication declares two exclude filters on its @ComponentScan: a TypeExcludeFilter and an AutoConfigurationExcludeFilter. The second one skips any class that is listed as an auto-configuration. This matters because auto-configuration must be applied in a controlled order, after your own beans are known. If component scanning registered those classes directly, they would be processed as ordinary configuration and their ordering and back-off logic would break.
@EnableAutoConfiguration
@EnableAutoConfiguration is the part that gives Boot its "it just works" behavior. It is meta-annotated with two things:
@AutoConfigurationPackagerecords the package of your main class. Libraries use that recorded package later. Spring Data JPA, for example, scans it for@Entityclasses and repositories, so you do not have to declare them.@Import(AutoConfigurationImportSelector.class)hands control to a selector that decides which configuration classes to load.
What the import selector does
When the context starts, AutoConfigurationImportSelector goes through these steps:
- It reads every file named
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importson the classpath. Each line in those files names one auto-configuration class. - It removes duplicates.
- It removes any class excluded through the
excludeorexcludeNameattributes, or through thespring.autoconfigure.excludeproperty. - It filters the remaining candidates by cheap conditions, such as whether a required class is present on the classpath, before loading them.
- It sorts the survivors according to their ordering rules.
- It imports them into the context, where each class's own conditions are evaluated as the context builds its bean definitions.
The result is a list of configuration classes that is built from your classpath, not from anything you wrote. Adding spring-boot-starter-web puts a web server and Spring MVC classes on the classpath. Their auto-configurations then pass their @ConditionalOnClass checks, and the beans appear.
An important consequence follows. Auto-configuration is not magic scanning of your code. It is a list of ordinary @Configuration classes, loaded late, guarded by conditions. Everything that holds for a normal configuration class holds for them. They declare @Bean methods, they can be injected with properties, and they can be tested like any other configuration.
Excluding from the annotation
You can turn off specific auto-configurations right on the annotation:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}When the class is not on the classpath of your compile step, use excludeName with the fully qualified name as a string. The same exclusion is available without code changes through a property:
# application.properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationUse the property when you want to change behavior per environment, such as in a test profile. Use the attribute when the exclusion is a permanent fact about the application. A later chapter compares exclusion with other ways to override defaults.
Using the pieces separately
@SpringBootApplication is a convenience, and you can replace it with its parts. This is useful when you want auto-configuration but a different scan, or the reverse.
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.example.shop.web")
public class NarrowApplication {
public static void main(String[] args) {
SpringApplication.run(NarrowApplication.class, args);
}
}This variant scans only the web package but still applies auto-configuration. If you write @ComponentScan yourself like this, add the same exclude filters when you scan broadly, or keep your scan away from auto-configuration packages.
You can also import specific configuration classes with @Import and skip scanning entirely, which gives very explicit wiring at the cost of more annotations to maintain.
Common errors
| Symptom | Likely cause |
|---|---|
| `NoSuchBeanDefinitionException` for your own `@Service` | The class is outside the package of the main class, so it was never scanned. |
| Startup fails with a message about a missing `DataSource` URL | A starter such as JDBC is on the classpath, so `DataSourceAutoConfiguration` applied, but no connection properties were supplied. Provide them or exclude the class. |
| Tests report more than one `@SpringBootConfiguration` | Two classes with `@SpringBootApplication` exist in the search path. |
| Entities or repositories are not found | The main class sits in a sub-package, so the recorded auto-configuration package does not cover them. |
| An exclusion has no effect | The attribute names a class that is not the one that actually applied. Check the conditions report. |
Summary of the mechanism
The three annotations divide the work cleanly. @SpringBootConfiguration says where the root configuration lives. @ComponentScan registers the beans you wrote. @EnableAutoConfiguration registers beans the framework decides you need, based on the classpath and properties. Your own beans are registered first, which is what allows auto-configuration to notice them and back off.
Exercise
A project has the main class com.example.app.App annotated with @SpringBootApplication. A @Service class lives in com.example.billing. At startup, injecting it fails with NoSuchBeanDefinitionException. Explain why, and give two ways to fix it.
Show answer
@ComponentScan with no arguments scans only com.example.app and its sub-packages, so com.example.billing is never scanned and the service is never registered. Fix 1: move the main class to a common parent package such as com.example. Fix 2: widen the scan with @SpringBootApplication(scanBasePackages = {"com.example.app", "com.example.billing"}). Declaring the service as a @Bean or using @Import also works.
Exercise
Why does @SpringBootApplication exclude auto-configuration classes from its own component scan, and which annotation actually loads them?
Show answer
Auto-configuration classes must be processed after the application's own beans are defined, in a controlled order, so that conditions such as @ConditionalOnMissingBean can see what the user already declared. If component scanning registered them as ordinary configuration, that ordering and back-off behavior would break. @EnableAutoConfiguration, through AutoConfigurationImportSelector, loads them from the AutoConfiguration.imports files.