Week 3 Day 3 — Auto-Configuration Deep Dive: Conditions, Back-Off, and Debugging
Goal
Today I want to understand Spring Boot auto-configuration deeply.
Main questions:
- What is auto-configuration?
- How does Spring Boot decide what to configure?
- What are conditions?
- What is
@ConditionalOnClass? - What is
@ConditionalOnMissingBean? - What is
@ConditionalOnProperty? - What does “auto-configuration backs off” mean?
- How can I override auto-configuration?
- How can I exclude auto-configuration?
- How can I debug auto-configuration decisions?
- What are common exam traps?
1. Quick Review from Week 3 Day 2
In Day 2, I learned:
- Starters are dependency bundles.
- Starters bring libraries onto the classpath.
- Auto-configuration configures beans based on those libraries.
- Spring Boot dependency management provides compatible versions.
- Usually I do not specify versions manually for Boot-managed dependencies.
Memory sentence:
Starters bring libraries.
Auto-configuration configures them.
Today I go deeper into how auto-configuration actually decides what to create.
2. What Is Auto-Configuration?
Auto-configuration is Spring Boot’s mechanism for automatically configuring Spring beans.
Simple definition:
Auto-configuration creates and configures beans automatically based on classpath, properties, existing beans, and conditions.
Example:
If I add:
implementation("org.springframework.boot:spring-boot-starter-web")
Spring Boot sees web-related classes and configures:
embedded Tomcat
Spring MVC
DispatcherServlet
HTTP message converters
Jackson JSON support
error handling
I do not need to configure these manually.
3. Why Auto-Configuration Exists
Without auto-configuration, I would need many configuration classes.
Example web app setup could require manual configuration for:
DispatcherServlet
HandlerMapping
HandlerAdapter
MessageConverters
ObjectMapper
Embedded Tomcat
Error handling
Static resources
Validation
Spring Boot says:
If common libraries are present and no custom bean overrides them, I can configure sensible defaults.
Memory sentence:
Auto-configuration removes common manual setup.
4. Auto-Configuration Is Not Magic
Spring Boot looks magical, but it is based on rules.
It checks:
1. Is a class present on the classpath?
2. Is a property enabled?
3. Is this a web application?
4. Does a required bean already exist?
5. Is a bean missing?
6. Is a profile active?
7. Did the user exclude this auto-configuration?
Then it decides whether to create beans.
Memory sentence:
Spring Boot auto-configuration is conditional configuration.
5. The Main Idea: Conditions
Auto-configuration uses conditions.
A condition says:
Apply this configuration only if something is true.
Common conditions:
@ConditionalOnClass
@ConditionalOnMissingBean
@ConditionalOnBean
@ConditionalOnProperty
@ConditionalOnWebApplication
@ConditionalOnNotWebApplication
@ConditionalOnResource
@ConditionalOnExpression
You do not need to memorize every detail.
But for the certification, you should understand the important ones.
6. Example Auto-Configuration Class
Simplified example:
@AutoConfiguration
@ConditionalOnClass(ObjectMapper.class)
public class JacksonAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
Meaning:
If ObjectMapper is on the classpath,
and no ObjectMapper bean already exists,
then create a default ObjectMapper bean.
This is the core idea of auto-configuration.
7. @ConditionalOnClass
@ConditionalOnClass means:
Apply this configuration only if a specific class exists on the classpath.
Example:
@ConditionalOnClass(ObjectMapper.class)
Meaning:
Only activate this configuration if ObjectMapper is available.
Why useful?
Because Spring Boot can detect which libraries I added.
Example:
Jackson class present -> configure JSON support
JPA class present -> configure JPA support
Spring MVC class present -> configure web MVC
Security class present -> configure security
8. Classpath-Driven Configuration
If I add this starter:
implementation("org.springframework.boot:spring-boot-starter-web")
I get Spring MVC classes on the classpath.
Then Spring Boot can say:
Spring MVC is available.
This is probably a servlet web app.
I should configure MVC infrastructure.
If I remove the starter, those classes are missing.
Then the related auto-configuration does not match.
Memory sentence:
What is on the classpath influences what Spring Boot auto-configures.
9. Real Example: Web Starter
Dependency:
implementation("org.springframework.boot:spring-boot-starter-web")
Classes appear on classpath:
DispatcherServlet
RequestMappingHandlerMapping
HttpMessageConverter
Tomcat classes
Jackson classes
Spring Boot auto-configures:
Spring MVC
embedded Tomcat
JSON converters
error handling
web application context
This is why adding one starter changes the application behavior.
10. @ConditionalOnMissingBean
@ConditionalOnMissingBean means:
Create this bean only if the user has not already defined a suitable bean.
Example:
@Bean
@ConditionalOnMissingBean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
Meaning:
If there is no ObjectMapper bean, create this default one.
If the user already created an ObjectMapper bean, do not create this one.
This is very important.
It allows Spring Boot to provide defaults but still let me override them.
11. What Does “Back Off” Mean?
When auto-configuration backs off, it means:
Spring Boot does not create its default bean because the user already provided one.
Example:
Spring Boot can create a default ObjectMapper.
But I define:
@Configuration
public class JsonConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper().findAndRegisterModules();
}
}
Then Boot may back off and not create its default ObjectMapper.
Memory sentence:
Back off means Boot steps aside when I provide my own bean.
12. Why Back-Off Is Useful
Back-off gives a good balance:
Spring Boot provides defaults.
I can customize when needed.
My custom bean can replace Boot’s default.
This is why Spring Boot is both:
opinionated
and:
customizable
Spring Boot gives sensible defaults, but it does not force them in every case.
13. @ConditionalOnBean
@ConditionalOnBean means:
Apply this configuration only if a specific bean already exists.
Example:
@Bean
@ConditionalOnBean(DataSource.class)
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
Meaning:
Create JdbcTemplate only if a DataSource bean exists.
This is useful because some beans only make sense if another bean is already available.
14. @ConditionalOnProperty
@ConditionalOnProperty means:
Create this bean only if a property has a certain value.
Example:
@Bean
@ConditionalOnProperty(
name = "feature.audit.enabled",
havingValue = "true"
)
public AuditService auditService() {
return new AuditService();
}
Configuration:
feature:
audit:
enabled: true
Result:
AuditService bean is created.
If the property is false or missing, the bean is not created.
15. @ConditionalOnProperty with matchIfMissing
Example:
@Bean
@ConditionalOnProperty(
name = "feature.audit.enabled",
havingValue = "true",
matchIfMissing = true
)
public AuditService auditService() {
return new AuditService();
}
Meaning:
Create the bean if feature.audit.enabled=true.
Also create it if the property is missing.
This is useful when a feature should be enabled by default.
16. Real Example: Feature Toggle
YAML:
feature:
email:
enabled: false
Config:
@Configuration
public class EmailConfig {
@Bean
@ConditionalOnProperty(
name = "feature.email.enabled",
havingValue = "true"
)
public EmailSender emailSender() {
return new SmtpEmailSender();
}
}
If feature.email.enabled=false, the bean is not created.
If another bean requires EmailSender, the app may fail unless there is another implementation or the dependency is optional.
17. @ConditionalOnWebApplication
@ConditionalOnWebApplication means:
Apply this configuration only if the application is a web application.
Example:
@ConditionalOnWebApplication
public class WebMvcAutoConfiguration {
}
This makes sense because web MVC beans should only be created for web apps.
A CLI app or batch job does not need:
DispatcherServlet
web error handling
web request mappings
18. @ConditionalOnNotWebApplication
Opposite idea:
@ConditionalOnNotWebApplication
Meaning:
Apply this only when the application is not a web application.
This can be useful for command-line or worker applications.
19. @ConditionalOnResource
@ConditionalOnResource means:
Apply configuration only if a resource exists.
Example idea:
@ConditionalOnResource(resources = "classpath:banner.txt")
This is less common in normal application code, but it appears in conditional configuration concepts.
20. @ConditionalOnExpression
@ConditionalOnExpression uses a SpEL expression.
Example:
@ConditionalOnExpression("${feature.advanced:false}")
Usually, prefer clearer conditions such as @ConditionalOnProperty.
For exam:
Know that condition annotations can use properties, beans, classes, web application type, or resources.
21. Auto-Configuration Decision Flow
Simplified flow:
1. Spring Boot finds auto-configuration classes.
2. It checks conditions.
3. If conditions match, bean definitions are registered.
4. If conditions do not match, configuration is skipped.
5. If user beans already exist, auto-configuration may back off.
6. ApplicationContext creates the final beans.
Memory sentence:
Auto-configuration classes are candidates. Conditions decide if they apply.
22. How Auto-Configuration Is Loaded
Spring Boot has auto-configuration classes provided by Boot and libraries.
Conceptually:
Spring Boot reads auto-configuration metadata.
It finds candidate auto-configuration classes.
It applies conditions.
Matching configurations contribute bean definitions.
You usually do not manually import these classes.
@EnableAutoConfiguration enables this mechanism.
And @SpringBootApplication includes @EnableAutoConfiguration.
23. Important: Auto-Configuration Runs with User Configuration
Spring Boot combines:
my @Configuration classes
my @Bean methods
my @Component classes
auto-configuration classes
external properties
Then it creates the application context.
The final application is a mix of:
my beans
Spring Framework infrastructure beans
Spring Boot auto-configured beans
third-party auto-configured beans
24. User Beans Usually Win
In many cases, user-defined beans have priority.
Example:
Boot wants to provide:
default ObjectMapper
But I provide:
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
Then Boot may not create its default because of:
@ConditionalOnMissingBean
Memory sentence:
Spring Boot prefers my explicit bean over its default when conditions are designed to back off.
25. Important: Not Every Auto-Configuration Backs Off the Same Way
Do not think all auto-configuration always backs off for everything.
Back-off depends on the condition used.
Example:
@ConditionalOnMissingBean
backs off when a bean exists.
But if the configuration does not use that condition, behavior may be different.
Exam-safe answer:
Many auto-configurations are conditional and often back off when suitable user beans exist, commonly using
@ConditionalOnMissingBean.
26. Overriding Auto-Configuration with Custom Beans
Example: custom Clock
@Configuration
public class TimeConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}
Any service can inject:
public TaskService(Clock clock) {
this.clock = clock;
}
If Boot or another library had a default Clock with @ConditionalOnMissingBean, my bean would cause it to back off.
27. Overriding ObjectMapper
Example:
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.findAndRegisterModules();
}
}
This can replace or customize the default JSON mapper.
But be careful.
If I fully replace Boot’s default ObjectMapper, I may lose some default customizations.
Sometimes better is to use customizers.
28. Customizer Pattern
Spring Boot often provides customizer interfaces.
Example concept:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> builder.indentOutput(true);
}
The idea:
Instead of replacing the whole auto-configured bean,
customize the bean creation process.
This is often safer than replacing the bean completely.
Memory sentence:
Prefer customizers when I only want to adjust Boot defaults.
29. Excluding Auto-Configuration
Sometimes I want to disable an auto-configuration.
Example:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class MyApplication {
}
This tells Spring Boot:
Do not apply DataSourceAutoConfiguration.
Use this when Boot is trying to configure something I do not want.
30. Exclude Auto-Configuration in Properties
Alternative:
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
This is useful when I want to configure exclusion without changing Java code.
31. When Should I Exclude Auto-Configuration?
Use exclusion carefully.
Possible cases:
Boot tries to configure a DataSource but the app has no database.
A library adds unwanted auto-configuration.
I want full manual control over a specific area.
A test wants to avoid expensive configuration.
But do not exclude randomly.
First understand why the auto-configuration matched.
Use:
debug logs
condition report
Actuator /actuator/conditions
32. Common Bug: DataSource Auto-Configuration
Dependency:
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
No datasource config.
Possible error:
Failed to configure a DataSource
Why?
Spring Boot sees JPA and database classes and tries to configure a DataSource.
Fix options:
configure spring.datasource.url
add database driver
add embedded database for tests
remove JPA starter if not needed
exclude DataSourceAutoConfiguration only if truly no DB is needed
33. Common Bug: Security Starter Changes Behavior
Dependency:
implementation("org.springframework.boot:spring-boot-starter-security")
After adding it, endpoints may require authentication.
Why?
Security auto-configuration matched because Spring Security is on the classpath.
Fix:
provide SecurityFilterChain bean
configure authorization rules
remove security starter if not needed
Example:
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health").permitAll()
.anyRequest().authenticated()
)
.build();
}
}
34. Common Bug: My Bean Is Not Used
Possible reasons:
My configuration class is outside component scanning.
My bean has wrong type.
There are multiple beans and no @Primary / @Qualifier.
An auto-configured bean is still used.
My bean is behind a profile that is not active.
A condition prevents my bean from being created.
The code injects a more specific type than my bean provides.
Debug with:
Actuator /actuator/beans
Actuator /actuator/conditions
startup logs
35. How to Debug Auto-Configuration
Good tools:
1. Run with --debug
2. Set debug=true
3. Use Actuator /actuator/conditions
4. Use Actuator /actuator/beans
5. Use Actuator /actuator/configprops
6. Read startup logs
7. Use dependency tree
36. --debug
Run:
java -jar app.jar --debug
or in application.yml:
debug: true
This prints an auto-configuration report in logs.
It shows:
positive matches
negative matches
unconditional classes
excluded classes
This helps answer:
Why did this auto-configuration apply?
Why did another one not apply?
37. Actuator Conditions Endpoint
Add Actuator:
implementation("org.springframework.boot:spring-boot-starter-actuator")
Expose conditions endpoint:
management:
endpoints:
web:
exposure:
include: health,info,conditions,beans,configprops
Then check:
/actuator/conditions
It shows condition evaluation.
This is one of the best debugging tools for auto-configuration.
38. Actuator Beans Endpoint
Endpoint:
/actuator/beans
This helps answer:
Which beans exist?
What is the bean name?
What is the bean type?
Which resource/configuration created it?
What dependencies does it have?
Useful when I ask:
Is my bean actually registered?
Did Boot create another bean?
39. Actuator Config Props Endpoint
Endpoint:
/actuator/configprops
This helps inspect configuration properties.
Useful when I ask:
Did my @ConfigurationProperties bind correctly?
What values did Boot bind?
Which configuration properties beans exist?
Be careful with sensitive data.
Do not expose too much Actuator information publicly in production.
40. Condition Report: Positive and Negative Matches
A condition report often contains:
Positive matches:
- configurations that matched and applied
Negative matches:
- configurations that did not match and were skipped
Example concept:
WebMvcAutoConfiguration matched:
- found servlet web application
- found DispatcherServlet class
DataSourceAutoConfiguration did not match:
- no suitable DataSource property
- no embedded database found
This is how I stop guessing and start debugging.
41. Real Debug Flow
When auto-configuration surprises me, use this flow:
1. Check dependencies.
2. Check active profiles.
3. Check application properties.
4. Check whether my custom bean exists.
5. Check conditions endpoint or debug report.
6. Check bean list.
7. Decide whether to customize, define a bean, change properties, or exclude auto-configuration.
Memory sentence:
Debug auto-configuration with classpath, properties, beans, and conditions.
42. Auto-Configuration and Properties
Many auto-configurations are controlled by properties.
Example:
server:
port: 9090
This customizes embedded server port.
Example:
spring:
datasource:
url: jdbc:postgresql://localhost:5432/app
username: postgres
password: postgres
This gives DataSource auto-configuration what it needs.
Example:
management:
endpoints:
web:
exposure:
include: health,info,metrics
This customizes Actuator auto-configuration.
Memory sentence:
Properties customize auto-configuration.
43. Auto-Configuration and Profiles
Profiles can change auto-configuration behavior because profiles change properties and beans.
Example:
## application-dev.yml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/app_dev
## application-prod.yml
spring:
datasource:
url: ${DB_URL}
Same auto-configuration.
Different properties.
Different result.
44. Auto-Configuration and Existing Beans
Existing beans can change auto-configuration.
Example:
@Bean
public DataSource dataSource() {
return customDataSource();
}
If Boot sees that a DataSource bean already exists, some auto-configuration may back off.
Example:
User-defined DataSource exists.
Boot does not create default DataSource.
45. Auto-Configuration and Ordering
Auto-configuration classes can have ordering rules.
You do not need to deeply memorize ordering for the exam.
But understand the idea:
Some auto-configurations need to run before or after others.
Spring Boot manages the order internally.
Example:
DataSource should exist before JdbcTemplate can be configured.
Exam-safe sentence:
Auto-configurations are ordered so dependent configurations can be applied in a sensible sequence.
46. Writing My Own Conditional Bean
I can also use conditional annotations in my own app.
Example:
@Configuration
public class AuditConfig {
@Bean
@ConditionalOnProperty(
name = "app.audit.enabled",
havingValue = "true"
)
public AuditService auditService() {
return new AuditService();
}
}
YAML:
app:
audit:
enabled: true
This creates AuditService.
If false, it does not.
47. Conditional Bean vs Profile
Use @Profile for environment:
@Profile("dev")
Use @ConditionalOnProperty for feature/config switches:
@ConditionalOnProperty(name = "feature.audit.enabled", havingValue = "true")
Memory sentence:
Profiles are for environments. Properties are better for feature switches.
48. Example: Better Than Too Many Profiles
Avoid:
dev-with-audit
dev-without-audit
prod-with-audit
prod-without-audit
Better:
profiles:
dev
prod
property:
feature.audit.enabled=true/false
Profiles describe environment.
Properties describe feature behavior.
49. Auto-Configuration in Tests
Tests can be affected by auto-configuration.
Example:
@SpringBootTest
loads a full application context and applies auto-configuration.
Slice tests load only part of the app.
Examples:
@WebMvcTest
@DataJpaTest
@JsonTest
These tests use limited auto-configuration for a specific layer.
We will study testing later.
Memory sentence:
Different test annotations load different parts of auto-configuration.
50. Common Exam Traps
Trap 1
Auto-configuration is not the same as component scanning.
Component scanning finds my annotated classes.
Auto-configuration applies Boot configuration classes conditionally.
Trap 2
Starters do not configure beans by themselves.
Starters bring dependencies.
Auto-configuration configures beans.
Trap 3
Auto-configuration is conditional.
It depends on:
classpath
properties
existing beans
web application type
conditions
Trap 4
@ConditionalOnMissingBean allows Boot to back off.
Trap 5
Adding a starter can change behavior.
Example:
Adding security starter can secure endpoints.
Adding JPA starter can trigger DataSource configuration.
Trap 6
application-prod.yml does not load unless prod profile is active.
That profile can affect auto-configuration.
Trap 7
Excluding auto-configuration should be done carefully.
Usually first debug why it matched.
Trap 8
Defining a custom bean may override Boot defaults.
But not every auto-configuration backs off in the same way.
Trap 9
Actuator /actuator/conditions helps debug auto-configuration.
Trap 10
debug=true or --debug can show condition evaluation in logs.
51. Real Exam Question: Auto-Configuration
Question:
What is Spring Boot auto-configuration?
Answer:
Auto-configuration is Spring Boot’s mechanism for automatically configuring beans based on classpath dependencies, application properties, existing beans, conditions, active profiles, and application type.
52. Real Exam Question: Conditions
Question:
Why does Spring Boot use conditions?
Answer:
Spring Boot uses conditions so that configuration is applied only when it makes sense. For example, web MVC configuration should apply only when web MVC classes are on the classpath and the app is a web application.
53. Real Exam Question: @ConditionalOnClass
Question:
What does @ConditionalOnClass do?
Answer:
It activates configuration only if a specific class is present on the classpath.
54. Real Exam Question: @ConditionalOnMissingBean
Question:
What does @ConditionalOnMissingBean do?
Answer:
It creates a bean only if no suitable bean already exists in the application context. This allows auto-configuration to back off when the user defines a custom bean.
55. Real Exam Question: Back-Off
Question:
What does it mean that auto-configuration backs off?
Answer:
It means Spring Boot does not create its default bean because a suitable user-defined bean already exists.
56. Real Exam Question: @ConditionalOnProperty
Question:
What does @ConditionalOnProperty do?
Answer:
It activates configuration or creates a bean only when a specific property has a matching value.
57. Real Exam Question: Starter vs Auto-Configuration
Question:
What is the difference between a starter and auto-configuration?
Answer:
A starter brings dependencies onto the classpath. Auto-configuration uses classpath, properties, existing beans, and conditions to configure Spring beans.
58. Real Exam Question: Debugging
Question:
How can I debug auto-configuration decisions?
Answer:
I can run the app with --debug or debug=true, check startup logs, and use Actuator endpoints such as /actuator/conditions, /actuator/beans, and /actuator/configprops.
59. Real Exam Question: Excluding Auto-Configuration
Question:
How can I exclude an auto-configuration class?
Answer:
I can use:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
or set:
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
60. Real Exam Question: Component Scan vs Auto-Config
Question:
What is the difference between component scanning and auto-configuration?
Answer:
Component scanning finds my application classes annotated with stereotypes such as @Service, @Repository, and @Controller. Auto-configuration applies Spring Boot configuration classes conditionally based on classpath, properties, and existing beans.
61. Interview Answer
Question:
Explain Spring Boot auto-configuration.
Good answer:
Spring Boot auto-configuration automatically configures Spring beans based on what it finds in the application. It checks classpath dependencies, application properties, existing beans, active profiles, application type, and conditions. For example, if Spring MVC and Tomcat are on the classpath, Boot can configure a servlet web application. Auto-configuration is conditional and often backs off when I provide my own bean.
62. Interview Answer
Question:
What does it mean that auto-configuration is conditional?
Good answer:
It means Spring Boot does not blindly configure everything. Auto-configuration classes and bean methods have conditions, such as @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, and @ConditionalOnWebApplication. These conditions decide whether a configuration should apply. This allows Spring Boot to adapt to the dependencies and settings of the application.
63. Interview Answer
Question:
What does auto-configuration back-off mean?
Good answer:
Back-off means Spring Boot chooses not to create a default bean because the user has already defined a suitable bean. This is commonly implemented with @ConditionalOnMissingBean. It allows Boot to provide useful defaults while still letting developers customize the application by defining their own beans.
64. Interview Answer
Question:
How do you override Spring Boot auto-configuration?
Good answer:
I can override auto-configuration by defining my own bean of the required type, changing configuration properties, using customizer beans, or excluding a specific auto-configuration class if necessary. Usually I first try to customize with properties or customizers. If I need full control, I can define my own bean. Excluding auto-configuration should be done carefully after understanding why it matched.
65. Interview Answer
Question:
How do you debug auto-configuration problems?
Good answer:
I check the dependencies, active profiles, and application properties first. Then I use --debug or debug=true to see the condition evaluation report. If Actuator is enabled, I check /actuator/conditions to see which auto-configurations matched or did not match, /actuator/beans to see which beans exist, and /actuator/configprops to inspect configuration properties.
66. Tiny Code Practice
Create a conditional bean:
@Configuration
public class AuditConfig {
@Bean
@ConditionalOnProperty(
name = "app.audit.enabled",
havingValue = "true"
)
public AuditService auditService() {
return new AuditService();
}
}
Config:
app:
audit:
enabled: true
Questions:
- Is
AuditServicecreated? - What happens if
app.audit.enabled=false? - Is this better as a profile or property?
Answers:
- Yes.
- No, the bean is not created.
- It is better as a property because this is a feature switch, not an environment.
67. Tiny Bug Practice 1 — DataSource
Problem:
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
Error:
Failed to configure a DataSource
Question:
Why did this happen?
Answer:
The JPA starter brings JPA and database-related classes onto the classpath. Spring Boot’s DataSource auto-configuration matches and tries to create a DataSource. If no database URL, driver, or embedded database is available, the app fails.
Fix options:
configure datasource
add database driver
use embedded database for tests
remove JPA starter if not needed
exclude DataSourceAutoConfiguration only if truly no database is needed
68. Tiny Bug Practice 2 — Security
Problem:
You add:
implementation("org.springframework.boot:spring-boot-starter-security")
Suddenly all endpoints require login.
Question:
Why?
Answer:
Spring Security is now on the classpath. Security auto-configuration matches and applies default security behavior. To customize it, define a SecurityFilterChain bean or configure security properties.
69. Tiny Bug Practice 3 — Custom Bean Not Used
Problem:
You create:
@Configuration
public class MyJsonConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
But it seems not to affect JSON behavior.
Possible reasons:
configuration class is outside component scan
another ObjectMapper is used
multiple ObjectMapper-like beans exist
custom bean has wrong type
test slice does not load this configuration
profile or condition prevents config from loading
Debug with:
/actuator/beans
/actuator/conditions
debug logs
Practice Questions and Answers
Question 1
What is auto-configuration?
Answer:
Auto-configuration is Spring Boot’s mechanism for automatically configuring beans based on classpath dependencies, properties, existing beans, conditions, active profiles, and application type.
Question 2
Why does Spring Boot use auto-configuration?
Answer:
Spring Boot uses auto-configuration to reduce manual setup and provide sensible defaults for common application features such as web, JPA, security, JSON, and Actuator.
Question 3
Why is auto-configuration not magic?
Answer:
Auto-configuration is not magic because it is based on clear mechanisms: classpath detection, conditional annotations, external properties, existing beans, and the Spring IoC container.
Question 4
What are conditions?
Answer:
Conditions are rules that decide whether a configuration class or bean should be applied.
Question 5
What does @ConditionalOnClass do?
Answer:
@ConditionalOnClass applies configuration only if a specific class is present on the classpath.
Question 6
What does @ConditionalOnMissingBean do?
Answer:
@ConditionalOnMissingBean creates a bean only if no suitable bean already exists.
Question 7
What does auto-configuration back-off mean?
Answer:
Back-off means Spring Boot does not create its default bean because the user already provided a suitable bean.
Question 8
What does @ConditionalOnBean do?
Answer:
@ConditionalOnBean applies configuration only if a specific bean already exists.
Question 9
What does @ConditionalOnProperty do?
Answer:
@ConditionalOnProperty applies configuration only if a specific property has a matching value.
Question 10
What does @ConditionalOnWebApplication do?
Answer:
@ConditionalOnWebApplication applies configuration only if the application is a web application.
Question 11
What is the difference between component scanning and auto-configuration?
Answer:
Component scanning finds my application classes annotated with stereotypes like @Service, @Repository, and @Controller. Auto-configuration applies Spring Boot configuration classes conditionally based on classpath, properties, existing beans, and application type.
Question 12
What is the difference between a starter and auto-configuration?
Answer:
A starter brings dependencies onto the classpath. Auto-configuration configures beans based on those dependencies and other conditions.
Question 13
How can I override a Boot default bean?
Answer:
I can override a Boot default bean by defining my own bean of the same expected type, changing configuration properties, using a customizer, or excluding the auto-configuration if necessary.
Question 14
Why might a customizer be better than replacing a whole bean?
Answer:
A customizer is often better because it adjusts Boot’s default configuration without replacing the whole bean and losing other Boot-provided customizations.
Question 15
How can I exclude an auto-configuration class?
Answer:
I can exclude an auto-configuration class with:
@SpringBootApplication(exclude = SomeAutoConfiguration.class)
or with:
spring:
autoconfigure:
exclude:
- fully.qualified.AutoConfigurationClassName
Question 16
When should I exclude auto-configuration?
Answer:
Exclude auto-configuration only when I understand why it matched and I truly do not want it. Usually I should first try properties, custom beans, or customizers.
Question 17
How can I debug auto-configuration?
Answer:
I can debug auto-configuration with --debug, debug=true, startup logs, Actuator /actuator/conditions, /actuator/beans, /actuator/configprops, and dependency tree tools.
Question 18
What does /actuator/conditions show?
Answer:
/actuator/conditions shows which auto-configuration conditions matched or did not match and why.
Question 19
What does /actuator/beans show?
Answer:
/actuator/beans shows which beans exist in the application context, including bean names, types, dependencies, and sources.
Question 20
Why can adding a starter change application behavior?
Answer:
Adding a starter puts new classes on the classpath. Auto-configuration may detect those classes and create new beans or change default behavior, such as enabling security or configuring a DataSource.
Final Memory Sentences
- Auto-configuration is conditional bean configuration.
- Spring Boot checks classpath, properties, existing beans, profiles, and application type.
@ConditionalOnClasschecks if a class exists.@ConditionalOnMissingBeancreates a bean only if no suitable bean exists.- Back-off means Boot does not create its default because I provided my own bean.
@ConditionalOnBeanrequires an existing bean.@ConditionalOnPropertydepends on property values.@ConditionalOnWebApplicationdepends on web application type.- Starters bring dependencies; auto-configuration configures them.
- Component scanning finds my classes; auto-configuration applies Boot configuration.
- Properties customize auto-configuration.
- Custom beans can override Boot defaults.
- Customizers can adjust Boot defaults safely.
- Auto-configuration can be excluded, but carefully.
- Use
--debugordebug=trueto inspect auto-configuration decisions. - Use Actuator
/actuator/conditionsto debug matching conditions. - Use Actuator
/actuator/beansto see registered beans.