Spring Boot core: how the application is put together
Spring Boot runs all five of your applications (Arena, the simulator, the detector, the Judge service and both command-line tools). This module explains what Spring actually does when it "starts": inversion of control, dependency injection, beans, auto-configuration, configuration properties, events, scheduling and Actuator, plus what changed in Spring Boot 4.
By the end you can answer
- "What are inversion of control and dependency injection?"
- "Why constructor injection over field injection?"
- "What does
@SpringBootApplicationdo? How does auto-configuration work?" - "What is a bean's scope and lifecycle? Are Spring beans thread-safe?"
- "How does
@Transactionalwork under the hood, and what is the self-invocation problem?" - "How do you bind and validate configuration? What is the property precedence order?"
- "What changed in Spring Boot 4?"
1. The problem Spring solves
Look at MatchService's constructor: it needs eight collaborators (three repositories, an event publisher, properties, a clock, a meter registry, a transaction manager), and each of those needs its own. Without a framework, main() would have to create hundreds of objects in exactly the right order and pass them around by hand. Change one constructor and you fix twenty call sites.
Inversion of control (IoC) flips the responsibility: your classes just declare what they need, and a container creates the objects and hands each one its dependencies. Handing over the dependencies is called dependency injection (DI).
Without IoC, every cook buys their own knives, pans and ingredients before cooking: duplicated, slow and inconsistent. With IoC, the head chef (the Spring container) sets up each station with exactly what is listed on that station's card (the constructor). The cook just cooks. And to test a new cook, you can set up their station with plastic knives (mocks) without changing how they work.
2. Beans and the application context
A bean is simply an object that Spring creates and manages. All beans live in the ApplicationContext (the container). There are two ways to declare one:
a) Annotate a class (component scanning)
| Annotation | Meaning | Example |
|---|---|---|
@Component | A generic bean | LeaderboardSync, FlagListener, StreamsWiring |
@Service | Business logic (same as @Component, clearer intent) | MatchService, JudgeService |
@Repository | Data access; also translates database exceptions into Spring's DataAccessException hierarchy | Spring Data creates repository beans from interfaces such as PlayerRepository |
@RestController | A web controller whose return values are written as JSON | MatchController |
@Configuration | A class that declares beans with @Bean methods | SecurityConfig, JwtConfig, KafkaConfig |
Spring finds these by component scanning: starting from the package of the class annotated @SpringBootApplication (for example dev.fairplay.arena) and every package below it.
Telemetry's TopicsConfig lives in dev.fairplay.telemetry.common, which is a sibling of dev.fairplay.telemetry.detector, not below it. Scanning never finds it. Each app therefore declares @Import(TopicsConfig.class) explicitly on its application class. A classic "why isn't my bean created?" bug.
b) A @Bean method inside a @Configuration class
Use this for objects you don't own (library classes) or that need custom construction:
@Configuration
public class ClockConfig {
@Bean
Clock clock() {
return Clock.systemUTC();
}
}
Now any bean that declares a Clock constructor parameter receives this one, and a test can replace it with a fixed clock. SecurityConfig declares the SecurityFilterChain and PasswordEncoder this way, and JwtConfig the encoder, decoder and key.
3. Dependency injection: constructor injection
There are three ways to inject. All of your code uses the first one only, and the projects' conventions require it.
| Style | Looks like | Verdict |
|---|---|---|
| Constructor | public MatchService(MatchRepository repo, ...) { this.repo = repo; } | Preferred |
| Field | @Autowired private MatchRepository repo; | Avoid |
| Setter | @Autowired void setRepo(MatchRepository r) | Only for optional dependencies |
Why constructor injection wins:
- Fields can be
final, so the object is fully built and never half-initialised. - Dependencies are visible in the signature. A constructor with 12 parameters is an honest signal that the class does too much.
- Testable without Spring:
new DecisionPolicy(settings)in a plain unit test. Field injection needs reflection or a Spring context. - Fails fast: a missing dependency fails at startup, not with a
NullPointerExceptionat the first request. - No
@Autowiredneeded when a class has exactly one constructor.
Telemetry's VerifierRunner has two constructors: a public one for Spring and a package-private one taking a Clock, for tests. With two constructors Spring cannot tell which to use, so the public one is marked @Autowired. The unit tests built the class by hand and never noticed. Only VerifierContextTest, which starts the whole Spring context, caught it. The lesson, written in the README: "coverage only says a line ran".
Injecting optional and multiple beans
Optional<ArenaPlayerRegistrar>(inSimulationEngine): empty when the bean doesn't exist.List<SomeInterface>: Spring injects every bean implementing the interface.- Two beans of the same type: disambiguate with
@Qualifier("name")or mark one@Primary.
4. Scope, lifecycle and thread safety
By default every bean is a singleton: one instance per application context, shared by all threads. Other scopes exist (prototype: a new instance per injection; request and session in web apps), but singleton is what you used everywhere.
Spring does nothing to make them thread-safe. A singleton service is called by many request threads at once, so it must be stateless (only final references to other beans) or protect its state. Your services are stateless. The few that hold state do it safely: StatDistributionService keeps its snapshot in an AtomicReference, the Judge's ProcessedFlags uses concurrent structures, and Micrometer counters are thread-safe.
Lifecycle
- Instantiate (call the constructor, with dependencies injected).
@PostConstructmethods run (initialisation).- The context finishes refreshing; web servers and listeners start;
ApplicationReadyEventis published. - The application runs.
- On shutdown,
@PreDestroymethods run (cleanup).
LeaderboardRebuilder.onApplicationReady()andStatDistributionService.refresh()listen forApplicationReadyEvent: the app is fully wired, so it is safe to query the database.SimulationEngine.start()starts the simulation on its own thread atApplicationReadyEvent, so the Actuator endpoints stay responsive. Its@PreDestroy stop()interrupts the thread and shuts down the executors.ProcessedFlagsLoader.onReady()replays thejudge-verdictstopic first, and only then starts the Kafka listener, which is declared withautoStartup = "false". The ordering guarantees a restarted Judge never judges a flag it already judged.
5. Proxies: how @Transactional and friends really work
Annotations like @Transactional, @PreAuthorize, @Async and @Cacheable are not magic. At startup Spring wraps the bean in a proxy: an object of a generated subclass (or one implementing the same interfaces) that sits in front of your object. Callers receive the proxy. When a method is called, the proxy runs extra behaviour before and after delegating to your real object:
caller ──► [ proxy: begin transaction ] ──► your MatchService.getMatch() ──► return
│ │
└────────────── commit (or roll back on exception) ◄──────┘
This technique is called AOP (aspect-oriented programming): cross-cutting concerns (transactions, security, metrics) are applied around methods without cluttering them.
The proxy only intercepts calls that come through the proxy. If a method inside the class calls another method of the same class (this.doSomething()), that call goes straight to the real object and skips the proxy, so @Transactional on doSomething() is silently ignored. The same applies to private methods, which proxies cannot intercept at all.
In your code: MatchService.recordMatch needs to run its work in a transaction and also catch the failure after the transaction has rolled back (a concurrent duplicate externalId). It uses a TransactionTemplate programmatically, recordTx.execute(status -> doRecordMatch(...)), inside a try/catch. That sidesteps the proxy question entirely and makes the transaction boundary explicit. AuthService builds a TransactionTemplate with REQUIRES_NEW for the same reason. Module 07 covers the transaction semantics.
@Configuration(proxyBeanMethods = false) (in the Judge's KafkaConfig and AnthropicConfig): normally Spring proxies a configuration class so that when one @Bean method calls another, you get the singleton rather than a new object. With false ("lite mode") there is no proxy, so startup is faster. It is safe when beans receive each other as method parameters (as yours do) instead of calling each other's methods.
6. Auto-configuration and starters
@SpringBootApplication combines three annotations:
@SpringBootConfiguration(a@Configuration),@ComponentScan(scan this package and below),@EnableAutoConfiguration: the heart of Boot.
Auto-configuration is a large set of @Configuration classes shipped inside Spring Boot, each guarded by conditions:
| Condition | Meaning | Example |
|---|---|---|
@ConditionalOnClass | Only if a class is on the classpath | PostgreSQL driver present, so configure a DataSource |
@ConditionalOnMissingBean | Only if you didn't define your own | Arena defines its own JwtDecoder, so Boot's default backs off |
@ConditionalOnProperty | Only if a property has a value | Your SimulationEngine: @ConditionalOnProperty(name = "telemetry.sim.autostart", havingValue = "true", matchIfMissing = true) |
So when you add PostgreSQL and Spring Data JPA, Boot sees the classes and configures a connection pool (HikariCP), an EntityManagerFactory, a transaction manager and Flyway, reading your spring.datasource.* properties. Define your own bean of the same type and Boot steps aside. That is "convention over configuration": sensible defaults, easy to override.
A starter is a dependency that pulls in a library together with its auto-configuration, for example spring-boot-starter-data-redis. You add the starter, not individual jars, and the Boot parent POM manages compatible versions.
- Telemetry's notes say: use
spring-boot-starter-kafka, because plainspring-kafkaon its own does not bring Boot 4's Kafka auto-configuration module, so nothing gets configured and nothing warns you. - Boot applies a single
CommonErrorHandlerbean to its default Kafka listener container factory automatically. That is why definingDefaultErrorHandleras a@BeaninBridgeErrorHandlingConfigand the Judge'sKafkaConfigis enough to wire retries and dead-lettering.
7. Externalised configuration
Code should not contain environment-specific values (URLs, passwords, timeouts). Spring reads them from many property sources, merged in a fixed precedence order. The ones you'll meet, from highest to lowest priority:
- Test properties (
@SpringBootTest(properties = ...),@DynamicPropertySource) - Command-line arguments (
--server.port=9000) - OS environment variables (
SERVER_PORT=9000) application-{profile}.ymlapplication.ymlinside the jar- Defaults in code
Relaxed binding maps SERVER_PORT (environment style) to server.port, and access-token-ttl in YAML to accessTokenTtl in Java.
spring:
datasource:
url: ${DB_URL:jdbc:postgresql://localhost:5432/arena} # env var DB_URL, or this default
arena:
jwt:
secret: ${JWT_SECRET} # no default: must be provided
access-token-ttl: 15m # binds to a java.time.Duration
Telemetry's .env file sets SERVER_PORT=8082 for the detectors. The simulator's YAML says server.port: 8081, but it shares the same .env, and an environment variable beats YAML, so the simulator would start on 8082. Compose sets SERVER_PORT: "8081" explicitly for the simulator to fix it. Knowing the precedence order turns this from "Spring is weird" into a one-line explanation.
Profiles (spring.profiles.active=prod) load extra files such as application-prod.yml and activate beans annotated @Profile("prod"). Don't confuse them with Docker Compose profiles (--profile sim), which only decide which containers start.
Importing files: the Judge's service and eval apps both start with spring.config.import: classpath:judge-defaults.yml, so the two programs always judge with identical settings from a single file inside judge-core.
8. Type-safe configuration with @ConfigurationProperties
Reading properties one at a time with @Value("${arena.jwt.secret}") scatters string keys across the code. Instead, bind a whole tree to a record:
@Validated
@ConfigurationProperties("arena")
public record ArenaProperties(
@NotNull @Valid Jwt jwt,
@NotNull @Valid Rating rating,
... ) {
public record Jwt(
@NotBlank @Size(min = 32) String secret, // HS256 needs a 256-bit key
@NotBlank String issuer,
@NotNull Duration accessTokenTtl,
@NotNull Duration refreshTokenTtl) {}
public record Moderation(
@NotNull @DecimalMin("0.0") @DecimalMax("1.0") BigDecimal serviceBanMinConfidence) {}
}
ArenaApplication has @ConfigurationPropertiesScan, so the record becomes a bean. With @Validated, a JWT secret shorter than 32 characters stops the application at startup with a message naming arena.jwt.secret. That is far better than a confusing crypto error at the first login.
| Project | How settings are validated | Why |
|---|---|---|
| Arena | Jakarta Bean Validation annotations + @Validated | Simple and declarative |
| Telemetry | Compact constructors that throw (DetectionProperties, SimulatorProperties) | Cross-field rules (players must be a multiple of match-size × shard-threads) and Duration checks that annotations can't express |
| Judge | Compact constructors, with the record bound by Spring's Binder (Binder.get(environment).bind("judge", JudgeSettings.class)) | judge-core has no Spring dependency, so the record cannot carry Spring annotations; the service binds it from outside |
Arena's arena.accounts.services is a list of two accounts in YAML. The integration tests overrode only services[0].password and services[1].password. Boot does not merge lists across property sources: the higher-priority source replaces the whole list, so the usernames became null, validation failed, and no integration test could start. The fix was to repeat the usernames in the test properties. A real bug you found by running the suite.
Failing fast on missing secrets
The Judge's StartupChecks bean reads the environment and throws if ANTHROPIC_API_KEY or the Arena password is missing. Its message names what is missing and never prints the value. AnthropicConfig takes StartupChecks as a constructor parameter purely to force it to run before the client is built. Using a dependency to control creation order is a neat trick.
9. Application events
Spring has a built-in, in-process publish/subscribe mechanism. A bean publishes an object; any bean with a matching listener method receives it. The publisher doesn't know who listens.
// Publisher (MatchService)
eventPublisher.publishEvent(new RatingChanged(player.getId(), ratingAfter));
// Listener (LeaderboardSync)
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onRatingChanged(RatingChanged event) {
redisTemplate.opsForZSet().add(leaderboardKey, event.playerId().toString(), event.rating());
}
@EventListenerruns immediately and synchronously, on the publishing thread.@TransactionalEventListener(AFTER_COMMIT)holds the event and runs it only if and after the surrounding transaction commits. If the transaction rolls back, the listener never runs, so Redis never sees a rating that doesn't exist in PostgreSQL. This is the core of Arena's cache consistency (module 08).
These events live in memory. If the process crashes after the database commit but before the listener updates Redis, the update is lost (Redis is then rebuilt from PostgreSQL at the next startup if the counts differ, and arena.leaderboard.sync.failures counts listener errors). Guaranteed delivery would need a transactional outbox: write the event to a table in the same transaction, then publish from that table. Arena's README lists it as the next step.
10. Scheduling and command-line apps
@EventListener(ApplicationReadyEvent.class)
@Scheduled(fixedDelayString = "${arena.stats.refresh-interval}") // 60s
public void refresh() { ... }
- Needs
@EnableScheduling(onArenaApplication). fixedDelay: wait 60 s after the previous run finishes, so runs never overlap.fixedRate: start every 60 s regardless.cron: calendar-based.- In a cluster of several Arena instances, every instance runs the job. That is fine here (each caches its own percentiles) but wrong for "send the daily email". For jobs that must run once, use a distributed lock such as ShedLock.
Command-line apps. Telemetry's verifier and the Judge's eval tool are Spring Boot apps with spring.main.web-application-type: none (no web server). VerifierRunner implements CommandLineRunner (runs once after startup with the arguments) and ExitCodeGenerator, so the process exits with a meaningful code: 0 ok, 1 integrity failed, 2 threshold missed, 3 run not finished, 4 bad arguments. Scripts and CI can act on that code.
11. Actuator: health, metrics and probes
Spring Boot Actuator adds production endpoints under /actuator. Your apps expose health, info, metrics and prometheus.
/actuator/healthaggregates health indicators (database, Redis, disk, and your own) intoUP/DOWN. Arena enables probes:/actuator/health/liveness("is the process alive, or should it be restarted?") and/actuator/health/readiness("can it take traffic yet?"). Kubernetes uses these two differently: a failing liveness probe restarts the pod, a failing readiness probe only removes it from the load balancer./actuator/prometheusexposes every Micrometer metric in Prometheus' text format (module 14).
@Component
class KafkaStreamsHealthIndicator implements HealthIndicator {
public Health health() {
KafkaStreams streams = factoryBean.getKafkaStreams();
if (streams == null) return Health.outOfService().withDetail("state", "NOT_CREATED").build();
Health.Builder builder = switch (streams.state()) {
case RUNNING -> Health.up();
case CREATED, REBALANCING -> Health.outOfService();
default -> Health.down();
};
return builder.withDetail("state", streams.state().name()).build();
}
}
A custom indicator reports the Streams client's state, so during a rebalance the instance reports "out of service" rather than "up". In Boot 4 these classes live in org.springframework.boot.health.contributor, a package that moved from older versions.
Arena leaves /actuator/prometheus unauthenticated for local scraping, and its README says so. In production you would expose Actuator on a separate management port or internal network, or require an admin role.
12. Logging
- Code logs through SLF4J (a facade); Boot uses Logback underneath. Lombok's
@Slf4jcreates thelogfield. - Always use placeholders:
log.info("Recorded match {} with {} participants", id, n). The message is only built if the level is enabled, and it avoids string concatenation. - All apps set
logging.structured.format.console: ecs: each log line is a JSON object in the Elastic Common Schema, ready for a log platform to index. - What not to log: secrets, tokens, passwords, personal data. The Judge's rules go further: never log prompt text, tool results or evidence text, only ids, token counts and status.
FlagListenerrefuses to put a malformed flag's JSON in the exception message "because it is a player's data".
13. What is different in Spring Boot 4 (and why online examples mislead you)
Spring Boot 4 (on Spring Framework 7) is recent, and most tutorials online show Boot 2 or 3. Your projects' notes list the differences that bit them:
| Topic | Older examples | Your Boot 4 code |
|---|---|---|
| Starters | spring-boot-starter-web | spring-boot-starter-webmvc; auto-configuration is split into smaller modules, each with a matching -test starter |
| JSON | Jackson 2, com.fasterxml.jackson.databind.ObjectMapper | Jackson 3, tools.jackson.databind.json.JsonMapper (annotations such as @JsonInclude stay in com.fasterxml.jackson.annotation) |
| Mocking beans in tests | @MockBean | @MockitoBean |
| MockMvc auto-config | org.springframework.boot.test.autoconfigure.web.servlet | org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc |
| Health API | org.springframework.boot.actuate.health | org.springframework.boot.health.contributor |
| Testcontainers | 1.x, PostgreSQLContainer<?> | 2.x, org.testcontainers.postgresql.PostgreSQLContainer (no generic) |
| Namespace | javax.* (Boot 2) | jakarta.* (since Boot 3) |
"I built on Spring Boot 4.1, which meant a lot of online examples were out of date: Jackson 3 moved packages, @MockBean became @MockitoBean, and starters were split. When an import didn't resolve, I read the release notes instead of downgrading." That shows you work with current tools and debug from primary sources.
14. Interview questions
What are IoC and DI? Basic
Inversion of control means the framework, not my code, creates objects and controls their lifecycle. Dependency injection is how it supplies each object's collaborators, through the constructor in my code. Classes declare what they need; the container builds the object graph. The payoff is loose coupling and testability: AgentLoop depends on a MessagesGateway interface, so production injects the real resilient gateway and tests inject a scripted fake.
Why constructor injection rather than @Autowired fields? Basic
Final fields and fully built objects; explicit, visible dependencies; plain unit tests without a container; fail-fast startup; and no @Autowired needed with a single constructor. Field injection hides dependencies, needs reflection to test and allows half-built objects. All three projects use constructor injection only.
What does @SpringBootApplication do? Basic
It combines @Configuration, @ComponentScan (this package and below) and @EnableAutoConfiguration, which loads Boot's conditional configuration classes. Those classes create beans such as the DataSource, JPA, Kafka templates and security defaults based on the classpath and properties, and back off when I define my own bean.
How does auto-configuration decide what to create? Intermediate
Each auto-configuration class is guarded by conditions: @ConditionalOnClass (is the library present?), @ConditionalOnMissingBean (did the user already define one?), @ConditionalOnProperty and others. Boot lists the candidate classes in a file inside each auto-configure jar and evaluates the conditions at startup. You can see the decisions with --debug (the conditions evaluation report). I used @ConditionalOnProperty myself on the simulator's engine so tests can start a context without launching a run.
Are Spring beans thread-safe? Intermediate
Not automatically. Singletons are shared by all request threads, so they must be stateless or guard their state. My services hold only final references to other beans. Where I need shared state, I use thread-safe constructs: an AtomicReference holding an immutable snapshot (percentiles), concurrent maps, and Micrometer meters, which are thread-safe.
How does @Transactional work, and when does it silently not work? Deep
Spring wraps the bean in a proxy; calls through the proxy start a transaction, call the real method, and commit, or roll back on an unchecked exception. It silently does nothing for (1) self-invocation (this.method() bypasses the proxy), (2) private or final methods, which a proxy can't intercept, (3) beans not managed by Spring, and (4) checked exceptions, which don't trigger rollback by default unless you set rollbackFor. In MatchService I needed to catch a unique-violation after rollback, so I used TransactionTemplate to make the boundary explicit and catch outside it.
What's the difference between @Component and @Bean? Basic
@Component (and @Service etc.) goes on a class I own and is discovered by scanning. @Bean goes on a factory method in a @Configuration class, for objects I don't own or that need custom construction: the Clock, PasswordEncoder, JwtDecoder, the Anthropic client, Kafka error handlers.
How do you validate configuration, and why at startup? Intermediate
Bind properties to a record with @ConfigurationProperties and validate: in Arena with @Validated and Bean Validation (@Size(min=32) on the JWT secret); in Telemetry and the Judge in compact constructors for cross-field rules. Failing at startup with the property name is far better than failing at 3 a.m. on the first request that touches it. The Judge also refuses to start without its API key and names the missing variable without printing values.
Explain @TransactionalEventListener(AFTER_COMMIT) and its limitation. Deep
The event is held until the surrounding transaction commits, then delivered; on rollback it is discarded. Arena uses it to update the Redis leaderboard only after PostgreSQL commits, so Redis never shows uncommitted ratings. The limitation is that the event lives in memory: a crash between commit and listener loses the update, and a listener failure is only logged and counted. Arena mitigates with a startup rebuild when counts differ; the robust fix is a transactional outbox.
An environment variable and application.yml both set server.port. Which wins? Intermediate
The environment variable: OS environment beats packaged YAML (command-line arguments and test properties beat both). This actually happened in Telemetry: a shared .env set SERVER_PORT=8082 for the detectors and overrode the simulator's 8081 from YAML, so Compose sets it explicitly for the simulator.
Your verifier's unit tests passed but the app couldn't start. Why? Curveball
VerifierRunner had two constructors, one for Spring and a package-private one for tests. Spring can't choose between multiple constructors without guidance, so context startup failed. Unit tests built the class with new and never exercised Spring's wiring. I fixed it with @Autowired on the public constructor and added VerifierContextTest, which starts the full context. The broader lesson: 100% line coverage didn't catch a wiring bug, so I keep at least one test that starts the real context.
What are liveness and readiness probes? Intermediate
Liveness answers "is this process healthy, or should it be restarted?". Readiness answers "should it receive traffic right now?". A service warming caches or rebalancing is alive but not ready. Arena enables both under /actuator/health/liveness and /readiness. The detector's custom indicator reports OUT_OF_SERVICE during a rebalance, which maps naturally onto readiness.
Why did you need @Import(TopicsConfig.class)? Curveball
Component scanning starts at the application class's package. TopicsConfig sits in the shared telemetry.common package, a sibling of each app's package, so scanning never reaches it. @Import registers it explicitly. The alternative, widening scanBasePackages, would also pull in everything else in common.
What does proxyBeanMethods = false change? Deep
Normally a @Configuration class is subclassed with CGLIB so that a call from one @Bean method to another returns the container's singleton. With false there's no proxy, so startup is faster and memory use lower, but a direct inter-method call would create a second instance. It is safe when, as in the Judge's config classes, beans get their dependencies as method parameters.
15. Quick quiz
1. A @Transactional method is called from another method in the same class. What happens?
Self-invocation bypasses the proxy, so the annotation does nothing (unless the caller already had a transaction).
2. Which bean scope is the default?
One shared instance per context, which is why beans must be stateless or thread-safe.
3. You define your own JwtDecoder bean. Boot's auto-configured decoder:
Auto-configuration yields to user-defined beans.
4. A test overrides arena.accounts.services[0].password only. The YAML list had usernames. Result?
Boot replaces lists from a higher-priority source; it doesn't merge them.
5. @Scheduled(fixedDelay = 60000) means:
fixedDelay measures from the end of the last run; fixedRate from its start.
6. What happens to an AFTER_COMMIT event if the transaction rolls back?
That's the point: no Redis update for data that never committed.
16. Cheat sheet
- IoC/DI: the container builds the object graph; constructor injection, final fields.
- Beans:
@Component/@Service/@Repository/@RestController(scanned) or@Beanin@Configuration. Scanning covers this package and below; otherwise@Import. - Singleton by default, so beans must be stateless or thread-safe.
- Proxies/AOP power
@Transactional,@PreAuthorize. Self-invocation and private methods bypass them; useTransactionTemplatefor explicit boundaries. - Auto-config: conditional configuration (
OnClass,OnMissingBean,OnProperty); starters bring it in. - Config precedence: test > command line > environment > profile YAML > YAML > defaults. Lists are replaced, not merged.
@ConfigurationPropertiesrecords + validation, so failure happens at startup with the property name.- Events:
@EventListener(now) vs@TransactionalEventListener(AFTER_COMMIT)(after commit; in memory; an outbox for guarantees). - Lifecycle: constructor →
@PostConstruct→ApplicationReadyEvent→ … →@PreDestroy. - Actuator: health (+ liveness/readiness), metrics, prometheus; custom
HealthIndicator. - Boot 4:
starter-webmvc, Jackson 3 (tools.jackson),@MockitoBean, the health package moved, Testcontainers 2.