Spring Boot from the inside: auto-configuration, configuration, profiles and the startup lifecycle
How auto-configuration is found and switched on, @Conditional and backing off, writing your own auto-config with tests, configuration precedence, @ConfigurationProperties, profiles, the phases of SpringApplication.run, seed data and graceful shutdown on Spring Boot 4.
On this page
Add one dependency and your app suddenly has Tomcat, a DataSource or security; this post opens up the mechanism. Afterwards you can read the condition report, write an auto-config with tests, tell which config value wins and which startup phase your code runs in. Read REST API and Spring Boot project structure and IoC and Dependency Injection first.
1. The problem
A team declares its own ObjectMapper in an @Configuration class with @ConditionalOnMissingBean. It works on the dev machine; on staging the JSON shows times in the wrong zone. The scan order changed, the default bean won, with no error at all.
2. Key idea
Boot reads the auto-config list from every jar, runs it after your configuration, and enables only the classes whose conditions hold. Because it runs later, when an auto-config asks "is there a DataSource yet?", your beans are already registered.
| Condition | Active when | Example |
|---|---|---|
@ConditionalOnClass |
the class is on the classpath | a JDBC driver means a pool is configured |
@ConditionalOnMissingBean |
no bean of that type yet | your own ObjectMapper means Boot creates none |
@ConditionalOnProperty |
a property has a given value | spring.jpa.open-in-view |
2.1 How do you override a default?
| Approach (light → heavy) | Use when | Don't use when |
|---|---|---|
| Change a property | Boot already has one (server.port, spring.jackson.time-zone) |
|
| Declare a bean of the same type | you need config no property offers | inside a plain @Configuration with @ConditionalOnMissingBean |
exclude the whole auto-config |
you want the feature gone | you only need to change one value |
Boot 4 splits auto-configs into modules per technology: DataSourceAutoConfiguration lives in org.springframework.boot.jdbc.autoconfigure. An exclude written for Boot 3 needs a new import.
2.2 Which value wins?
| Precedence | Source |
|---|---|
| 1 | command line: --server.port=9090 |
| 2 | environment variable: SERVER_PORT=9090 |
| 3 | profile file: application-prod.properties |
| 4 | application.properties / .yml (same location: .properties wins) |
- Relaxed binding:
app.jwt.access-ttlandAPP_JWT_ACCESSTTLare the same property. - Profiles switch bean groups and files per environment. They don't hold secrets: the files live in Git and in the jar.
- Lifecycle: an
ApplicationRunnerruns once the context is ready; if it throws, the app doesn't start. Background work starts afterApplicationReadyEvent.
3. In Java
@ConfigurationProperties(prefix = "app.jwt")
public record JwtProperties(String secret, Duration accessTtl, Duration refreshTtl) {
public JwtProperties {
if (secret == null || secret.isBlank())
throw new IllegalStateException("app.jwt.secret is required");
}
}
// application.properties
// app.jwt.secret=${JWT_SECRET}
// app.jwt.access-ttl=15m -> Duration.ofMinutes(15)
// app.jwt.refresh-ttl=7d -> Duration.ofDays(7)
// JWT_SECRET missing -> the app won't start, the error names the property@Value suits a single value; from three properties with the same prefix, group them into a record. Other languages: Go uses a struct + envconfig; Node.js checks process.env with a zod schema at startup.
Writing your own auto-configuration
@AutoConfiguration
@ConditionalOnProperty(prefix = "hr.audit", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties.class)
public class AuditAutoConfiguration {
@Bean @ConditionalOnMissingBean(AuditLogger.class)
AuditLogger auditLogger(AuditProperties p) { return new Slf4jAuditLogger(p.prefix()); }
}Register the class name in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Test it with ApplicationContextRunner: a tiny context, a few milliseconds per test, no @SpringBootTest. Check three cases: the default bean exists, it backs off when the app has its own bean, and a property turns it off.
4. Working with AI
Give the AI: turning scattered @Value into @ConfigurationProperties, and writing ApplicationContextRunner tests for an auto-config.
Check in AI-written code:
-
@ConditionalOnMissingBeanappears only in@AutoConfigurationclasses registered via.imports. - No real secrets in
application-*.properties; only${DB_PASSWORD}. - No folder has both
application.propertiesandapplication.yml. - Required config is checked at startup, not at the first request.
5. Exercises
Exercise 1: Config "ignored"
The refresh token TTL is 3d in application.yml, but the app uses 7 days. Staging also has an APP_JWT_REFRESHTTL variable. The AI suggests "switch to @Value to be safe". How do you find the cause?
Solution to Exercise 1
@Value doesn't change precedence, so the suggestion fixes nothing. Open /actuator/env/app.jwt.refresh-ttl (authenticated): it shows which source the active value comes from.
Two suspects: the APP_JWT_REFRESHTTL environment variable (beats every file), or an application.properties in the same folder saying 7d (.properties beats .yml). Fix it by keeping one file format and removing the stray variable.
Exercise 2: Where to configure ObjectMapper
JSON must write times in UTC. The AI offers three ways: (A) an @Configuration class with @Bean @ConditionalOnMissingBean ObjectMapper; (B) the property spring.jackson.time-zone=UTC; (C) exclude Jackson's auto-config and configure everything yourself. Which one?
Solution to Exercise 2
Pick B: a property is the lightest option, and Boot still configures the rest (Java time module, Spring MVC wiring). For deeper tweaks, declare a customizer bean that Jackson's auto-config picks up, still without replacing the mapper.
(A) depends on scan order, which is exactly the incident in section 1. (C) loses every good default and leaves you maintaining it.
Summary
- Auto-configs load from
.imports, run after your beans, and back off when you already have one. - Override: property → same-type bean →
exclude; debug with the condition report. - Command line > environment variables > profile file > common file.
- Group config into
@ConfigurationPropertiesand fail fast at startup. - Read secrets from the environment, never from profile files.
Read more: Twelve-factor app.
Practice interview questions on this topic
- How does component scanning work? Why does Spring say a bean is missing even though the class has @Service?
- What does @SpringBootApplication consist of? How is a starter different from auto-configuration?
- How does Spring Boot auto-configuration work?
- A property in application.properties is overridden by another value. What do you check? @Value or @ConfigurationProperties?
- How do you package a shared internal library as a Spring Boot starter for many services?
- What are the steps of a bean's lifecycle? How do BeanPostProcessor and BeanFactoryPostProcessor differ?
Comments
Community rules