Sub topic 1
What auto-configuration does
Prerequisites
You should know Java and basic Maven or Gradle usage. You should also understand Spring dependency injection, @Configuration, @Bean, and external configuration in application.properties.
What auto-configuration does
Spring Boot auto-configuration creates common application beans based on the libraries and settings in your application. For example, a database driver on the classpath can activate database-related configuration.
@SpringBootApplication includes @EnableAutoConfiguration. This tells Spring Boot to find possible auto-configuration classes and evaluate their conditions. Auto-configuration supplies defaults, but it should not prevent customization. If you define your own bean, a well-designed auto-configuration usually backs off.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}How Spring Boot finds auto-configuration classes
Spring Boot discovers candidates from this file:
src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
Each line contains one fully qualified auto-configuration class name. Spring Boot loads these candidates and evaluates their conditions. A candidate becomes active only when its conditions match.
com.example.greeting.GreetingAutoConfigurationThe imports file is discovery metadata. It does not mean that every listed class will create beans.
Conditions: `@Conditional` and `Condition`
A condition is a rule that decides whether configuration should be processed. @Conditional connects configuration to a class implementing the Condition interface. Spring Boot provides ready-made annotations for common rules.
Conditions can inspect the classpath, beans, properties, resources, or application type. Multiple conditions normally all need to match.
Reacting to the classpath
@ConditionalOnClass matches when a named class is available. This lets an auto-configuration activate only when its supporting library is present.
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
public class GreetingAutoConfiguration {
}The opposite, @ConditionalOnMissingClass, matches when a class cannot be found. Keep class-dependent configuration isolated so missing optional dependencies do not cause class-loading failures.
Exercise
Why does a class listed in AutoConfiguration.imports not always create beans?
Show answer
Spring Boot treats the class as a candidate, then applies its conditions. If a condition fails, the auto-configuration is skipped.