Skip to content
notes.vinhnq.com

Search

SpringMid14 min read

Spring Boot from the inside: auto-configuration, configuration, profiles and the startup lifecycle

Review 13 cards
On this page

Add one dependency and your app suddenly has Tomcat, a DataSource or security; this post explains the mechanism so Spring Boot stops feeling like magic. Afterwards you can read the condition report, write an auto-configuration with tests, tell which configuration value wins, and know which startup phase your code runs in. Read the Spring Boot intro in REST API and Spring Boot project structure and IoC and Dependency Injection first.

1. How auto-configuration is found

Key idea: @SpringBootApplication turns on @EnableAutoConfiguration, which reads the class list from every AutoConfiguration.imports file on the classpath and activates only the classes whose conditions match.

@SpringBootApplication is three annotations in one:

  • @SpringBootConfiguration: this class is a configuration source.
  • @ComponentScan: scans this class’s package and its sub-packages for @Component, @Service…
  • @EnableAutoConfiguration: loads auto-configuration.

Auto-configs don’t live in your packages, so the component scan can’t see them. Each Spring Boot module ships a META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports file, one class name per line. Boot reads them all, orders them (@AutoConfiguration(after = ...)), then evaluates each class’s conditions.

The key point: auto-configs are processed after your configuration (they come in through a DeferredImportSelector, an import selector that runs last). So when an auto-config asks “is there a DataSource bean yet?”, the bean you declared is already registered.

flowchart LR
  A["@SpringBootApplication"] --> B[Component scan: your beans]
  A --> C[Read AutoConfiguration.imports in every jar]
  B --> D[Register your bean definitions]
  C --> E{Conditions match?}
  D --> E
  E -->|yes| F[Register default beans]
  E -->|no| G[Skip]
Spring Boot 4: auto-configs split by module

Spring Boot 4 broke the huge spring-boot-autoconfigure jar into many small modules per technology. For example DataSourceAutoConfiguration now lives in org.springframework.boot.jdbc.autoconfigure inside the spring-boot-jdbc jar (checked in the 4.0.3 jar). In practice:

  • Boot 3 code like exclude = DataSourceAutoConfiguration.class needs a new import on Boot 4.
  • Starters were renamed too: spring-boot-starter-web became spring-boot-starter-webmvc. Tests get per-technology starters: spring-boot-starter-webmvc-test, spring-boot-starter-data-jpa-test, spring-boot-starter-security-oauth2-resource-server-test (exactly what the lab’s pom uses).
  • The payoff: a leaner classpath, fewer auto-configs to evaluate, faster startup.

Starters, BOMs and how Maven resolves versions belong to Maven and the layout of a Spring Boot project; here you only need: starters decide which libraries are on the classpath, auto-config decides which beans get created from them.

DevTools (spring-boot-devtools, runtime scope, optional) restarts the app automatically when classes change. It uses two classloaders: libraries sit in a fixed one, your code in one that gets recreated, so a restart is faster than a cold start. DevTools turns itself off under java -jar and never belongs in production.

2. Conditions and backing off

Key idea: every auto-config is a @Configuration class guarded by conditions. The most common one is @ConditionalOnMissingBean: create the default bean only if you haven’t created one.

Condition Active when Example in Boot
@ConditionalOnClass a class is on the classpath DataSource plus a JDBC driver present → set up a pool
@ConditionalOnMissingClass a class is not present
@ConditionalOnBean / @ConditionalOnMissingBean a bean of that type exists / doesn’t declare your own ObjectMapper and Boot stops creating one
@ConditionalOnProperty a property has a given value spring.jpa.open-in-view
@ConditionalOnWebApplication it’s a web app (servlet/reactive) DispatcherServlet setup
@ConditionalOnResource a file is on the classpath

Three ways to override a default, from light to heavy:

  1. Change a property: server.port=9090, spring.jackson.time-zone=UTC. Prefer this.
  2. Declare a bean of the same type: the auto-config sees yours and backs off.
  3. Exclude the whole auto-config: @SpringBootApplication(exclude = ...) or the spring.autoconfigure.exclude property.

Reading the condition report. Run java -jar app.jar --debug (or debug=true). The log prints the condition evaluation report with “Positive matches” (switched on, and why) and “Negative matches” (not switched on, what was missing). With Actuator, look at /actuator/conditions. That’s the answer to every “why does/doesn’t this bean exist” question.

3. Lab: writing your own auto-configuration

Key idea: write an auto-config with Boot’s own recipe (registered via .imports, guarded by conditions, able to back off) and test it with ApplicationContextRunner in milliseconds.

The task: the HR app needs audit logging (who did what to what). Provide a default AuditLogger that writes to SLF4J, but:

  • it can be switched off with hr.audit.enabled=false;
  • the prefix is configurable through hr.audit.prefix;
  • if the app declares its own AuditLogger, the default must disappear.
@AutoConfiguration
@ConditionalOnProperty(prefix = "hr.audit", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties.class)
public class AuditAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(AuditLogger.class)
    AuditLogger slf4jAuditLogger(AuditProperties props) {
        return new Slf4jAuditLogger(props.prefix());
    }
}

@ConfigurationProperties(prefix = "hr.audit")
public record AuditProperties(@DefaultValue("true") boolean enabled,
                              @DefaultValue("[audit]") String prefix) {}

Registered in src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:

dev.lab.hr.audit.AuditAutoConfiguration

The test doesn’t need @SpringBootTest. ApplicationContextRunner builds a tiny context per test:

private final ApplicationContextRunner runner = new ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class));

@Test
void backsOffWhenTheAppDefinesItsOwnBean() {
    runner.withUserConfiguration(CustomLogger.class).run(ctx -> {
        assertThat(ctx).hasSingleBean(AuditLogger.class);
        assertThat(ctx).doesNotHaveBean(Slf4jAuditLogger.class);
    });
}

@Test
void canBeSwitchedOffByProperty() {
    runner.withPropertyValues("hr.audit.enabled=false")
          .run(ctx -> assertThat(ctx).doesNotHaveBean(AuditLogger.class));
}

Run on JDK 21 with Spring Boot 4.0.3: all three tests (default bean gets the prefix, backs off for a custom bean, switched off by property) pass, the whole class in about 30 ms. The full lab mvn test: 29 tests, 28 passed, 1 skipped (the Testcontainers test; this machine couldn’t run Docker).

What a senior would add to this auto-config
  • Separate modules: a real auto-config lives in its own hr-audit-spring-boot-autoconfigure jar, plus an empty starter that only declares dependencies. Apps just add the starter.
  • Don’t pin the concrete type: @ConditionalOnMissingBean(AuditLogger.class) on the interface, so the app can swap in any implementation.
  • @ConditionalOnClass when the default needs an optional library (say Kafka): no library, the auto-config stays quiet instead of breaking the app.
  • IDE metadata: add spring-boot-configuration-processor so the IDE suggests hr.audit.* with descriptions.
  • Ordering: use @AutoConfiguration(after = ...) when your bean needs another auto-config’s bean.

4. External configuration: which value wins

Key idea: Spring Boot merges properties from many sources into one Environment. Higher-priority sources override lower ones; knowing this order solves 90% of “why isn’t my config applied”.

Order from highest to lowest (simplified):

  1. Command-line arguments: --server.port=9090.
  2. OS environment variables: SERVER_PORT=9090.
  3. Profile-specific files: application-prod.properties (outside the jar beats inside).
  4. Common files: application.properties / application.yml (outside the jar beats inside).
  5. Defaults in code (@DefaultValue).

This is the “config lives in the environment” idea from the twelve-factor app: the same jar, different environment variables for dev, staging and prod.

Relaxed binding: app.jwt.access-ttl, app.jwt.accessTtl and the environment variable APP_JWT_ACCESSTTL all point to the same property. For environment variables: replace . with _, drop -, upper-case it.

5. @ConfigurationProperties instead of scattered @Value

Key idea: bind a group of properties into a typed, validated record. Bad config kills the app at startup with a clear message instead of failing at 2 a.m.

The lab reads its JWT settings with a record:

@ConfigurationProperties(prefix = "app.jwt")
public record JwtProperties(String secret, String issuer, Duration accessTtl, Duration refreshTtl) {
    public JwtProperties {
        if (secret == null || secret.isBlank()) throw new IllegalStateException("app.jwt.secret is required");
    }
}
app.jwt.secret=${JWT_SECRET:...dev-only...}
app.jwt.access-ttl=15m
app.jwt.refresh-ttl=7d
@Value("${...}") @ConfigurationProperties
Scope one value a structured group
Types basic conversions Duration (15m), DataSize (5MB), lists, maps, nested records
Validation none record constructor or @Validated + Bean Validation
IDE hints no yes (with the configuration processor)
Relaxed binding limited full

@Value is still fine for a single value, such as the CORS origins list in the lab’s SecurityConfig. From three properties under one prefix upwards, use a properties class.

6. Profiles

Key idea: a profile is a label that switches groups of beans and config files on or off. Use it for differences between environments, not to store secrets.

  • Activate: --spring.profiles.active=dev or SPRING_PROFILES_ACTIVE=dev. Nothing active means the default profile.
  • Profile-specific files: application-dev.properties is loaded on top of application.properties and overrides it.
  • Profile-specific beans: the lab puts @Profile("dev") on DevSeedData, so sample data only appears in dev. Run: with --spring.profiles.active=dev the log shows The following 1 profile is active: "dev" and logging in with the seeded account returns 200.
  • Profile groups: spring.profiles.group.prod=prod-db,prod-mq so one name pulls in the whole group.

7. The startup lifecycle

Key idea: SpringApplication.run goes through fixed phases: prepare the Environment, create the context, refresh it (create beans, start the web server), run runners, and only then report ready. Knowing the phase tells you where your code belongs.

flowchart TB
  A["ApplicationStartingEvent"] --> B["Prepare Environment: read every property source, resolve profiles"]
  B --> C["Create ApplicationContext"]
  C --> D["refresh(): register bean definitions, run auto-config, create singletons, start Tomcat"]
  D --> E["ApplicationStartedEvent"]
  E --> F["CommandLineRunner / ApplicationRunner"]
  F --> G["ApplicationReadyEvent: readiness = ACCEPTING_TRAFFIC"]
  D -.failure.-> H["ApplicationFailedEvent + APPLICATION FAILED TO START"]

Where code goes:

  • Initialising one bean: the constructor or @PostConstruct. Don’t call other transactional services here.
  • Work that needs the full context (seed data, cache warm-up): ApplicationRunner or CommandLineRunner. Runners run before ApplicationReadyEvent; a runner that throws stops the app from starting.
  • Background work after the app is ready: listen for ApplicationReadyEvent.

Graceful shutdown: on SIGTERM the web server stops taking new requests, waits for in-flight ones within spring.lifecycle.timeout-per-shutdown-phase (30s by default), and only then destroys beans. Since Spring Boot 3.4 it’s on by default. That’s why you stop an app with kill (SIGTERM), not kill -9 (see common errors).

Three ways to seed data, and a correction to the course notes
Way Fits Notes
data.sql small, fixed dev data Runs by default for embedded DBs; others need spring.sql.init.mode=always. Runs before Hibernate creates tables unless you set spring.jpa.defer-datasource-initialization=true. Runs on every start: use INSERT ... ON CONFLICT/INSERT IGNORE to avoid duplicates
ApplicationRunner + @Profile("dev") dev data with logic (hash passwords, check if already there) The lab’s choice, idempotent via if (users.count() > 0) return;
Flyway / Liquibase data required in every environment (base permissions, the initial admin) Versioned, runs exactly once, history kept in its own table

The lab’s seed code:

@Component
@Profile("dev")
public class DevSeedData implements ApplicationRunner {
    @Override
    @Transactional
    public void run(ApplicationArguments args) {
        if (users.count() > 0) return;                       // already seeded
        Permission read = permissions.save(new Permission("GET_USER", "/api/v1/users/{id}", "GET", "USER"));
        Role admin = new Role("ADMIN");
        admin.getPermissions().add(read);
        roles.save(admin);
        User u = new User("Admin", "admin@example.dev", encoder.encode("change-me-123"), User.Gender.OTHER);
        u.getRoles().add(admin);
        users.save(u);
    }
}

Remember

  • Explain why component scanning doesn’t find auto-configs, and where they’re loaded from.
  • Know three ways to override a Boot default and how to read the condition report.
  • State the configuration precedence order, and what happens with both .properties and .yml.
  • Know when to use @ConfigurationProperties over @Value, and why failing fast matters.
  • Put code in the right place (constructor, runner, ApplicationReadyEvent) and explain graceful shutdown.

Interview questions

Junior

What does @SpringBootApplication consist of?

Three annotations: @SpringBootConfiguration, @ComponentScan (current package and sub-packages) and @EnableAutoConfiguration.

Because scanning starts at the main class’s package, that class should sit in the root package. Beans outside that package tree won’t be found.

How do you change the port or turn off an auto-configuration?

Changing a property (server.port=9090) is the lightest way; to turn one off completely use exclude on @SpringBootApplication or spring.autoconfigure.exclude.

The middle ground is declaring a bean of the same type; the auto-config backs off thanks to @ConditionalOnMissingBean.

Mid

How does auto-configuration work?

Boot reads @AutoConfiguration classes from the AutoConfiguration.imports files on the classpath, processes them after your configuration, and activates only those whose @Conditional... conditions match.

Typical conditions: a class on the classpath, a bean present or missing, a property value. Debug with --debug for the condition evaluation report, or /actuator/conditions.

A property is set in application.properties but the app sees a different value. What do you check?

The higher-priority sources: command-line args, environment variables, the active profile’s file, files outside the jar, and a .properties/.yml pair in the same place.

Check the active profiles in the startup log and the property’s source in /actuator/env. Remember relaxed binding: APP_JWT_SECRET overrides app.jwt.secret.

How do @Value and @ConfigurationProperties differ, and which do you pick?

@Value reads single values; @ConfigurationProperties binds a whole group into a structured type with validation and IDE hints.

For several properties under one prefix, use @ConfigurationProperties (a record) and validate so the app dies at startup when config is missing or wrong.

When does a CommandLineRunner run, and how is it different from @PostConstruct?

A runner runs after the context has refreshed and the web server has started, before ApplicationReadyEvent; @PostConstruct runs right after one bean is created.

In @PostConstruct, other beans may not be ready and the transactional proxy may not wrap the bean itself yet, so work like seeding data belongs in a runner.

Senior

You’re writing an internal library shared by many services. How do you package it as an auto-configuration?

An auto-configure module with an @AutoConfiguration class registered via the .imports file, guarded by conditions and @ConditionalOnMissingBean on interfaces, plus a starter that only pulls dependencies.

  • Properties under their own prefix, bound with @ConfigurationProperties, with the configuration processor.
  • @ConditionalOnClass for parts that depend on optional libraries.
  • Tests with ApplicationContextRunner: default on, backs off for a custom bean, off by property, missing library.
How does graceful shutdown work, and what else do you need for zero dropped requests during a deploy?

On SIGTERM the server stops accepting new requests, waits for in-flight ones within the phase timeout, then destroys beans; it’s on by default since Boot 3.4.

For rolling deploys you also need: readiness switching to refusing traffic before shutdown, the load balancer removing the instance in time, a shutdown timeout longer than your longest request, and stopping with SIGTERM rather than SIGKILL.

Useful phrases for interviews

  • “Auto-configuration only kicks in when its conditions match.”
  • “The auto-configuration backs off as soon as I declare my own bean.”
  • “I ran the app with –debug and read the negative matches in the condition evaluation report.”
  • “Environment variables take precedence over application.properties, and the command line beats both.”
  • “Thanks to relaxed binding, APP_JWT_SECRET maps to app.jwt.secret.”
  • “A missing secret should fail fast at startup, not at the first request.”
  • “Seed data only runs under the dev profile; required reference data goes into a Flyway migration.”
  • “Graceful shutdown lets in-flight requests finish before the context closes.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.