Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·46

Spring Core

Companion to Volume 3, chapter 46: how inversion of control, the container, the bean lifecycle and configuration, and AOP and proxies connect; new angles (a composition root as a kitchen's mise en place, a static constant as a recipe card glued to the wall, property sources as a stack of sticky notes); what the chapter simplifies, measured on the JDK and the build's stage 47 (Spring's own behaviour read from its source): a time zone setting that the JDK's older API turns into GMT when it's misspelt, the same order priced three ways by three zones because the zone was a constant nothing could inject, a property resolver that returns the first value it finds and says where only in its trace log, and business days of 23 and 25 hours; the theory behind them (composition roots, fail-fast configuration, time as configuration); how Spring guards against the GMT fallback and resolves properties, from its source; four debugging drills; interview questions with how to approach each.

6 sections · ~12 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 46 covers inversion of control (IoC and DI, injection styles), the container (the ApplicationContext, configuration styles, resolving ambiguity), the bean lifecycle and scopes, configuration and environment (profiles, property sources, application events) and AOP and proxies (aspects, how Spring's proxies work, DI and AOP in other ecosystems).

inversion of control the container lifecycle and config AOP and proxies IoC and DI the framework calls you injection styles constructor first composition root one place builds the graph hidden dependencies statics, lookups ApplicationContext bean definitions configuration styles scan, @Bean, functional ambiguity @Primary, @Qualifier, lists cycles fail at startup bean lifecycle create, inject, init, destroy scopes singleton, prototype, request environment profiles, property sources application events in-process, sync by default cross-cutting concerns transactions, caching proxies JDK or CGLIB self-invocation bypasses the proxy other ecosystems Guice, Dagger, Go by gathered in replaces from resolves or reports per configured by plus applied by trap: compare builds on: ch44 backend fundamentals (DI by hand) · ch40 JVM (class loading, proxies) · goes on: ch47 Spring Boot · ch48 Spring Web · ch49 persistence (transactions) exercises: P1–P9 qualifiers, lifecycle, full and lite config, events, property sources, proxies, a Spring-free domain, scopes, Guice and Go; C1–C3
Concept map of chapter 46, Spring Core: inversion of control (IoC and DI, injection styles), the container (ApplicationContext, configuration styles, resolving ambiguity), bean lifecycle and scopes, configuration and environment (profiles, property sources, application events), and AOP and proxies (aspects, how Spring's proxies work, DI and AOP in other ecosystems), with links such as constructor injection making dependencies visible and a proxy being what you get back.

The links worth remembering:

  • Dependencies you can see are dependencies you can change. Constructor injection, a composition root or a container all serve one goal: nothing reaches out for what it needs; it's handed in.
  • Configuration is a dependency too. A setting read from a static constant, a system property deep in the code or TimeZone.getDefault() is as hidden as a new buried in a method.
  • What you get back may be a proxy. Cross-cutting behaviour (transactions, caching, async) lives in a generated wrapper, with rules of its own (the chapter's lab).

Explain it differently

1. A composition root is a kitchen's mise en place. Before service, every ingredient is measured, chopped and set out where the cook will reach for it. During service nobody goes to the store. A program with a composition root builds every object once, at the start, and hands each one what it needs (Gaps 2).

2. A static constant is a recipe card glued to the wall. It works until a second kitchen, in another city, needs a different recipe. Then you have to unglue it, and find every cook who reads it (Gaps 2).

3. Property sources are a stack of sticky notes. The container reads from the top note down and takes the first answer it finds. A note lower down that says something else is never read, and nothing tells you it was there (Gaps 3).

4. A forgiving parser is a receptionist who guesses. Ask TimeZone.getTimeZone for "Asia/Calcuta" and it doesn't say "I don't know that place": it sends you to Greenwich (Gaps 1).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from OpenJDK 21.0.12 and the build's stage 47 (exp/47), unless stated.

1. A setting's type decides what a typo does. The chapter's configuration section binds strings to typed properties. For a time zone, Java has two APIs, and they disagree about mistakes:

Terminal
== a typo in the configured zone
  Asia/Kolkata   TimeZone.getTimeZone -> Asia/Kolkata   ZoneId.of -> Asia/Kolkata
  Asia/Calcuta   TimeZone.getTimeZone -> GMT            ZoneId.of -> throws ZoneRulesException: Unknown time-zone ID: Asia/Calcuta
  IST            TimeZone.getTimeZone -> IST            ZoneId.of -> throws ZoneRulesException: Unknown time-zone ID: IST
  +05:30         TimeZone.getTimeZone -> GMT            ZoneId.of -> +05:30

TimeZone.getTimeZone answers GMT for anything it doesn't recognise, including a perfectly good offset. It also accepts three-letter IDs like "IST", which mean India in Java and Israel or Ireland elsewhere. ZoneId.of refuses both. Spring converts strings to TimeZone through a helper that checks for exactly this fallback (Code walkthrough); code that calls TimeZone.getTimeZone itself gets no such check. Stage 47's Config reads the zone with ZoneId.of and refuses to start on a typo.

2. A constant is a dependency nothing can inject. TiffinBox priced every order in Server.BUSINESS_ZONE, a static constant that Pages also read directly. The same order, placed at the same instant, under the same rules (rules/november.rules), in three zones:

Terminal
== the same order priced in three zones (rules/november.rules)
  placed 2026-11-20T06:00:00Z, zone Asia/Kolkata     local 11-20 11:30  discount ₹0.00    free delivery true  rules Optional.empty
  placed 2026-11-20T06:00:00Z, zone GMT              local 11-20 06:00  discount ₹62.00   free delivery true  rules Optional[Breakfast at k7]
  placed 2026-11-20T06:00:00Z, zone America/New_York local 11-20 01:00  discount ₹62.00   free delivery true  rules Optional[Breakfast at k7]
  placed 2026-11-20T20:00:00Z, zone Asia/Kolkata     local 11-21 01:30  discount ₹62.00   free delivery false rules Optional[Breakfast at k7]
  placed 2026-11-20T20:00:00Z, zone GMT              local 11-20 20:00  discount ₹0.00    free delivery true  rules Optional.empty
  placed 2026-11-20T20:00:00Z, zone America/New_York local 11-20 15:00  discount ₹0.00    free delivery true  rules Optional.empty

"Breakfast before 11" and "weekday delivery" mean different instants in different places, so the zone is part of the price. With a constant, no test could check another zone, and a second deployment could only change it by editing code. Stage 47 makes it a dependency of a Pricer, built once in Main's composition root from configuration, and a test prices the same order in two zones. A container would have done the same thing; what matters is that the setting stopped being a static.

3. Property resolution takes the first value and stays quiet about the rest. The chapter lists the order of property sources. Spring's resolver walks them in that order and returns the first non-null value (Code walkthrough); which source supplied it is logged at debug level, if at all. Spring Boot adds origin tracking on top; Spring Framework alone doesn't record it. Stage 47's Config keeps the origin of each value and prints it:

Terminal
$ TIFFINBOX_IDLE=9s tiffinbox config DIR 18991 RULES --max-connections=60   (DIR/tiffinbox.properties: zone=Europe/London, idle=7s)
  data                 DIR  (command line)
  port                 18991  (command line)
  rules                RULES  (command line)
  zone                 Europe/London  (DIR/tiffinbox.properties)
  idle                 9s  (environment TIFFINBOX_IDLE)
  head-deadline        10s  (default)
  max-connections      60  (command line)
  access-log-capacity  10000  (default)

The file said idle=7s; the environment won, and the line says so. Without the origin, "why is the idle timeout 9 seconds?" means searching four places. Problems are collected rather than thrown one at a time:

Terminal
$ tiffinbox serve DIR 80x RULES --zone=Asia/Calcuta --idle=5 --colour=red
refusing to start: the settings can't be used:
  unknown option --colour (known: data, port, rules, web, zone, idle, head-deadline, max-connections, access-log-capacity)
  port: expected a whole number, got '80x'
  zone: Unknown time-zone ID: Asia/Calcuta (use a region such as Asia/Kolkata or Europe/London)
  idle: expected a number with a unit (ms, s or m), like 5s, got '5'
exit 78

Before, the same port typo gave Exception in thread "main" java.lang.NumberFormatException: For input string: "80x" and exit code 1, and --zone=… was taken as the web directory.

4. A zone is not an offset: business days are 23 and 25 hours. The chapter's examples configure values that stay put. A zone's rules change twice a year in much of the world:

Terminal
== how long is a business day?
  2026-03-29 in Asia/Kolkata     24 hours
  2026-03-29 in Europe/London    23 hours
  2026-10-25 in Europe/London    25 hours
  2026-03-08 in America/New_York 23 hours
  2026-11-01 in America/New_York 25 hours
  01:30 on 2026-03-29 in Europe/London, which doesn't exist, becomes 02:30

India has no daylight saving, so TiffinBox never met this. A kitchen in London would: a "between 1 and 2 am" rule never fires on one Sunday in March, and fires for two hours on one in October; a day's revenue report covers 23 or 25 hours. Configure a region (Europe/London), never a fixed offset (+00:00), and test the two transition days.

Common misconceptions

Misconception What's actually true Where it's shown
"A bad setting fails at startup." Only if its type refuses bad values; TimeZone turns them into GMT. Gaps 1
"IST is India Standard Time." In Java's TimeZone; elsewhere it's also Israel and Ireland. Use regions. Gaps 1
"A constant isn't a dependency." If it can differ between deployments or tests, it is. Gaps 2
"DI needs a container." A composition root does the same job by hand. Gaps 2
"Spring tells you where a property came from." Spring Boot does; the core resolver only logs it at debug level. Gaps 3
"Every day has 24 hours." Not in zones with daylight saving. Gaps 4
"Annotations work on any call." Not on calls from inside the bean (self-invocation). Chapter lab, Experiment 2

Theoretical gaps: the ideas behind the chapter

1. The composition root. Mark Seemann's term for the single place, as close to the program's entry point as possible, where the object graph is composed. Everything else receives its dependencies and never looks them up (no service locator, no static access). A DI container is one way to implement a composition root; hand-written wiring is another. The test of either: can a test build the same graph with one part replaced?

2. Fail fast, and all at once. Jim Shore's "fail fast" applies twice to configuration: refuse to start rather than run with a wrong value, and report every problem in one go rather than one per restart. Typed parsing at the boundary (Gaps 1) is what makes the first possible; collecting errors makes the second.

3. Ambient context. Values that code reaches for implicitly (the default time zone, the default locale, the current time, system properties) are ambient context. They make code depend on where it runs. Chapter 38's clock and stage 47's zone are the same move: make the ambient value an explicit dependency.

4. Time zones are data that change. The IANA time zone database (tzdata) is updated several times a year as governments change their rules. A zone ID is a reference into that data; the JDK ships a copy (updatable with the TZUpdater tool). A fixed offset is a snapshot that will be wrong after the next change.

Applying it

Code walkthrough

From spring-projects/spring-framework, main at commit 7ce40c8 (18 November 2026).

Refusing the GMT fallback

spring-core/src/main/java/org/springframework/util/StringUtils.java:

Java
	public static TimeZone parseTimeZoneString(String timeZoneString) {
		TimeZone timeZone = TimeZone.getTimeZone(timeZoneString);
		if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) {
			// We don't want that GMT fallback...
			throw new IllegalArgumentException("Invalid time zone specification '" + timeZoneString + "'");
		}
		return timeZone;
	}

Spring's TimeZoneEditor (used when a property is bound to a TimeZone) calls this, so a typo in a Spring-bound setting fails. The check is indirect: it can't ask TimeZone whether it recognised the name, so it looks for the symptom (a result of "GMT" for input that didn't say GMT). That also means +05:30, which TimeZone doesn't understand, is refused, while GMT+05:30 is accepted. Code that calls TimeZone.getTimeZone directly, or binds to a String and converts later, has no such guard (Gaps 1).

The first value wins

spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java:

Java
	protected <T> @Nullable T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) {
		if (this.propertySources != null) {
			for (PropertySource<?> propertySource : this.propertySources) {
				if (logger.isTraceEnabled()) {
					logger.trace("Searching for key '" + key + "' in PropertySource '" +
							propertySource.getName() + "'");
				}
				Object value = propertySource.getProperty(key);
				if (value != null) {
					...
					logKeyFound(key, propertySource, value);
					return convertValueIfNecessary(value, targetValueType);
				}
			}
		}

The property sources are an ordered list (system properties, then environment variables, then files, in a standard context; Spring Boot adds many more), and the loop returns from the first one that has the key. Lower sources are never consulted, so a value in a file that's shadowed by an environment variable is silently ignored. logKeyFound logs which source answered, at debug level. Conversion happens after resolution, so a bad value fails only when someone asks for it, not when the context starts, unless something binds it eagerly (Gaps 3).

Debugging drills

D1. Every order is a breakfast order

After a new deployment for a second city, a "before 11 am" discount applies to orders all evening. The configuration says business.zone=America/Chicago, and the code reads it with TimeZone.getTimeZone(env.getProperty("business.zone")).

D2. A setting that changes nothing

An operator sets idle=30s in the service's properties file to fix dropped connections; nothing changes, and a restart doesn't help.

D3. The variable that does nothing

A team sets TIFFINBOX_MAX_CONECTIONS=500 to protect a small machine. The server starts fine, and a load test shows it still accepting up to 2,000 connections.

D4. The report that loses an hour

A daily revenue report for a London kitchen shows a dip on the last Sunday of March and a spike on the last Sunday of October, every year.

Career-oriented

Interview prep

Mid-level 1: constructor or field injection

Question. "Why do most teams prefer constructor injection over @Autowired fields?"

How to get there. What each style allows a test, and what it tells a reader.

Mid-level 2: two beans of the same type

Question. "Spring fails at startup with expected single matching bean but found 2. What are your options?"

How to get there. Choose one, or ask for all.

Senior 1: configuration that can't be wrong

Question. "Design how a service's configuration is defined, loaded and validated."

How to get there. Types, sources, origins, failure.

Senior 2: multi-region time

Question. "We're opening kitchens in three new countries. What changes in how the service handles time?"

How to get there. Where local time is used, and who decides which zone.

Staff 1: a container or not

Question. "A new team argues that DI containers are unnecessary magic and wants to wire everything by hand. When do you agree?"

How to get there. What a container does beyond wiring, and what hand wiring costs as the graph grows.

Staff 2: removing ambient state from a codebase

Question. "Our monolith calls TimeZone.getDefault(), Locale.getDefault() and System.currentTimeMillis() in hundreds of places. Plan a cleanup."

How to get there. Find, replace with dependencies, keep it from coming back.