← All guides · It Works Locally

Spring Start Here, Retold

A Java developer's companion to Spring Start Here by Laurențiu Spilcă (Manning). The chapters follow the book; the stories and simulators are added on top. Get the book ↗

Published · Last checked against Spring Boot 4.1.1 and Spring Framework 7.0 on

Using this as a reference? for plain language with no stories. Your choice is remembered.

Compact view: plain language, no stories, simulators or deep dives.

Part 1 · chapters 1–6

Spring Core: the context, beans, wiring and aspects

Plain Spring (spring-context 7.0.8, the Spring Framework 7.0 that Spring Boot 4.1 is built on) on Java 17, no Spring Boot. Everything is done by hand, so you see exactly what Boot later does for you, and exactly how many ways it can die.

1
Ocean's Eleven

What Spring is and why it exists

As in Danny's crew, nobody in your app should recruit their own partners. Spring is a framework that creates your objects and connects them for you. Without it, every class builds the objects it depends on, and you assemble the whole app yourself, in the right order: new Heist(new Pickpocket(), new Driver(), ...). With Spring, you describe the objects, and Spring creates them and gives each one the others it needs. That is Inversion of Control (IoC): your code stops deciding when objects are created and how they are connected.

Comic-style portrait of Danny Ocean
Danny OceanThe container. He recruits the crew so nobody else has to.
Coupling, the problem Spring was built to solve

A class is tightly coupled when it builds its own dependencies. If Heist runs new Pickpocket() itself, it is welded to that class. To use a different pickpocket, or to hand it a stand-in for a rehearsal (a test), you have to edit Heist.

A class is loosely coupled when it only says what it needs (usually an interface, in its constructor) and lets someone else decide which implementation it gets. Three words name three layers of the same idea:

TermWhat it is
Inversion of ControlThe principle. Your code stops creating and connecting objects, and the framework does it instead.
Dependency injectionThe technique. Dependencies are handed in from outside, through the constructor, a setter or a field.
IoC container (the context)The thing that does it. In Spring it's the ApplicationContext.

Everything else in Spring is built on this. Aspects, transactions, web controllers and repositories only work because Spring owns the objects, which means it can wrap them, replace them or hand out copies.

The vocabulary

TermMeaningWhere you meet it
ContextThe container that holds every object Spring manages.new AnnotationConfigApplicationContext(...), and later SpringApplication.run
BeanOne object living in the context.Dealer, VoyageService, every controller
Dependency injection (DI)Spring hands a bean the other beans it needs.Constructor parameters everywhere
ProxyA wrapper Spring puts around a bean to add behaviour.Aspects (ch 6), @Transactional (ch 13), scoped beans (ch 9)
Auto-configurationSpring Boot creating beans for you based on your dependencies.JdbcTemplate, DataSource, the web server
Garbage collectorThe part of the JVM that deletes any object nothing points to any more. It isn't cruel. It's punctual.Every object you've ever created, eventually

The Spring family you touched

ProjectWhat it gives youChapters
Spring Framework (Core, AOP)Context, beans, DI, aspects2–6
Spring BootStarters, auto-configuration, embedded Tomcat, properties7–15
Spring MVCControllers, views, REST7–10
Spring Cloud OpenFeignDeclarative HTTP clients11
Spring Data JDBCRepositories generated from interfaces14
Spring SecurityLogin, passwords, access rulesPart 5
2
Ocean's Eleven

The context: three ways to add a bean

Rusty's notebook only works if Danny is told about every recruit. Write new Dealer() by hand and you've hired someone Danny never heard of: Spring doesn't know that object exists, so it can't inject it anywhere or manage its life. To make it a bean, Spring has to create it, or at least be told about it. Spring only manages objects it knows about. If you write new Dealer() yourself, Spring doesn't know that object exists, so it can't inject it anywhere or manage its life. An object Spring manages is called a bean. To make one, Spring has to create the object, or at least be told about it. There are three ways to do that.

Comic-style portrait of Rusty Ryan
Rusty RyanThe notebook: a @Configuration class with one @Bean method per page.
Comic-style portrait of Livingston Dell
Livingston Dell@Bean: hired by hand, like a library class you can't annotate.
Comic-style portrait of Basher Tarr
Basher Tarr@PostConstruct: briefed once, before he joins the crew.

0. Create the project and add Spring

The book opens chapter 2 by creating a plain Java project with a build tool, then adding exactly one dependency: spring-context. That single line is "adding Spring". There's no installer and no download page. The build tool fetches the jars from Maven Central and puts them on the classpath. The book uses Maven; Gradle does the same job, and both are shown below. Pick one tab and every build snippet on this page switches with it.

What a build tool does

Maven and Gradle do the same four jobs: download the libraries you declare (and the libraries they need), compile your code against them, run your tests, and package everything into a jar. You never copy jar files around by hand. You name a library by its coordinates, a group, an artifact and a version, and the tool does the rest.

ConceptMavenGradle
Build filepom.xml (XML)build.gradle (Groovy) or build.gradle.kts (Kotlin)
Coordinates<groupId>, <artifactId>, <version>One string: "group:artifact:version"
Needed to compile and rundefault scope (compile)implementation
Needed only at runtime (a JDBC driver)<scope>runtime</scope>runtimeOnly
Needed only by tests<scope>test</scope>testImplementation
Needed only to compile (Lombok)<optional>true</optional> or providedcompileOnly
Wrapper script (no install needed)./mvnw./gradlew
Build outputtarget/build/
Show every dependency, including indirect ones./mvnw dependency:tree./gradlew dependencies

Transitive dependencies. spring-context needs spring-core, spring-beans, spring-aop and spring-expression. You don't list them. The tool reads spring-context's own build file and pulls them in. That's why one line gives you the whole container.

The standard layout. Both tools expect the same folders: src/main/java for code, src/main/resources for config files, src/test/java for tests. So you can switch tools later without moving a single file.

pom.xml · plain Spring
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- your project's own coordinates -->
    <groupId>org.example</groupId>
    <artifactId>heist-crew</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>17</maven.compiler.release>
    </properties>

    <dependencies>
        <!-- this one dependency IS "adding Spring" -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>7.0.8</version>
        </dependency>
    </dependencies>
</project>
Running itMaven: ./mvnw compile, then run Main from the IDE (plain Maven has no run command without the exec plugin). Gradle: ./gradlew run.

1. @Bean methods in a @Configuration class

Here you create the object, and Spring keeps it. You write a class marked @Configuration, which tells Spring "this class holds bean definitions". Inside it, each method marked @Bean builds one object with plain new and returns it. At startup Spring calls every @Bean method once and adds whatever it returns to the context.

config/HeistPlan.java
@Configuration
public class HeistPlan {

    @Bean
    public Dealer dealer() {
        Dealer p = new Dealer();
        p.setName("Frank");
        return p;          // the returned object becomes a bean named "dealer"
    }
}

// Main.java
var context = new AnnotationConfigApplicationContext(HeistPlan.class);
Dealer p = context.getBean(Dealer.class);
  • The bean's name is the method's name, so this bean is called "dealer". To choose another name, write @Bean("frank").
  • new AnnotationConfigApplicationContext(HeistPlan.class) starts Spring and hands it the configuration class to read.
  • getBean(Dealer.class) asks the context for the bean of that type. Spring gives you the object it already holds; it does not create a new one.

Because you write the new yourself, this works for any class, including library classes you can't edit, and you can set up the object however you like before returning it. You can also have several beans of the same type, for example two Dealer methods named frank() and rusty(). Then getBean(Dealer.class) fails with NoUniqueBeanDefinitionException, because Spring can't tell which one you mean. Fix it in one of two ways:

config/HeistPlan.java + Main.java
@Bean
@Primary                 // the default when someone asks for "a Dealer"
public Dealer frank() { ... }

@Bean
public Dealer rusty() { ... }

// or ask for one by name
Dealer d = context.getBean("rusty", Dealer.class);

2. Stereotype annotations with component scanning

Here Spring creates the object. You put @Component on your own class, which means "Spring, make one of these". On its own that does nothing: Spring has to be told where to look. @ComponentScan on the configuration class gives it a package, and at startup Spring searches that package (and its sub-packages) for classes marked @Component, calls their constructor and adds each instance to the context.

crew/Dealer.java + config/HeistPlan.java
@Component
public class Dealer { ... }

@Configuration
@ComponentScan(basePackages = "org.example.crew")   // where to look for @Component classes
public class HeistPlan { }
  • The bean's name is the class name with a lowercase first letter, so this one is "dealer". Two exceptions: @Component("croupier") sets the name yourself, and a class whose first two letters are capitals keeps its name, so URLParser stays "URLParser". You get it the same way: context.getBean(Dealer.class).
  • @Component has three more specific versions, called stereotype annotations: @Service, @Repository and @Controller. They create a bean exactly the same way; the name just tells readers what the class does. You will use them from chapter 4 on.
  • Scanning registers one bean per class. You can't get two differently configured Dealer beans this way, and it only works for classes you can edit. For either of those, use @Bean methods. (How many instances that one bean produces is its scope, in chapter 5.)

This is much less code than writing a @Bean method for every class, which is why real apps use it for almost all of their own classes. The catch is that Spring calls the constructor, so you never get a chance to set anything on the object. This Dealer is born nameless: its name is null. To run setup code right after creation, use @PostConstruct:

crew/Dealer.java
@Component
public class Dealer {
    private String name;

    @PostConstruct            // runs once, right after Spring builds the object
    public void init() {
        name = "Frank";
    }
}
@PostConstruct needs one more dependency@PostConstruct and @PreDestroy live in jakarta.annotation, which isn't part of the JDK, so plain Spring won't compile them until you add the API. In Spring Boot you never see this, because the starters already include it.
pom.xml · inside <dependencies>
<!-- provides jakarta.annotation.PostConstruct and PreDestroy -->
<dependency>
    <groupId>jakarta.annotation</groupId>
    <artifactId>jakarta.annotation-api</artifactId>
    <version>3.0.0</version>
</dependency>

3. Programmatic registration

The first two ways are fixed when you write the code: Spring reads your @Bean methods and @Component classes at startup. Sometimes you only know at runtime whether a bean should exist, for example because it depends on a setting or a value the user typed. For that, you call registerBean() on the context yourself, from ordinary Java code, after the context has been created.

crew/Main.java
var context = new AnnotationConfigApplicationContext(HeistPlan.class);

Dealer x = new Dealer();
x.setName("Frank");
Supplier<Dealer> dealerSupplier = () -> x;   // tells Spring how to get the object

context.registerBean("dealer1", Dealer.class, dealerSupplier);

Dealer d = context.getBean(Dealer.class);      // Frank, now a bean like any other

registerBean() takes four things:

  • The name ("dealer1"). Pass null and Spring picks one.
  • The type (Dealer.class), so Spring knows what the bean is when another bean asks for a Dealer.
  • A Supplier, a small function that returns the object. Spring calls it when it needs the instance. Here it returns the Dealer you already built, but it could just as well be () -> new Dealer().
  • Optional customizers that set extra properties on the bean definition, for example making it the primary bean of its type, the one Spring picks when there are several Dealer beans:
crew/Main.java
context.registerBean("dealer1", Dealer.class, dealerSupplier,
        bc -> bc.setPrimary(true));             // customizer: mark it @Primary

The result is the same as with the other two ways: Spring now holds the object, you can get it with getBean(), and it can be injected into other beans. The difference is only when the decision is made. You will rarely need this, because @Component and @Bean cover almost every case, and Spring Boot's @ConditionalOnProperty handles most "only if" beans. Use it when the decision really can't be written down in advance.

What a bean really is, in memory

Here's the secret: a bean is an ordinary Java object. The only difference is who creates it and who keeps a reference to it, and the second part decides when it dies. Step through the code below. The stack holds your local variables, the heap holds the objects, and the arrows are references (addresses). Use the Next button or your arrow keys. Watch for the moment the last arrow to an object disappears. That's when the garbage collector comes.

Try it · Ocean's Eleven: Rusty's notebook, inside memory
From new AnnotationConfigApplicationContext to context.close()
Step 1
Ocean's Eleven · the notebook
Stack · main thread
Heap · every object
Console output

Which one to use

ApproachUse it whenLimit
@Component + scanThe class is yours. This is the default in real apps.One instance per class
@BeanThe class is from a library (HikariDataSource, RestClient), or you need several configured instances.More code
registerBeanBeans decided at runtime (rare).Hard to read
Common mistakes
  • A @Component class outside the scanned package is silently ignored. There's no warning at startup. You find out later from NoSuchBeanDefinitionException, which is how most of us find out we were never invited.
  • Two beans of the same type and getBean(Dealer.class) gives NoUniqueBeanDefinitionException. Spring will not choose between them. Ask by name instead: getBean("dealer1", Dealer.class).
  • A @Bean method's name is the bean's name. Rename the method and every @Qualifier("oldName") that pointed at it now points at nobody.
Lifecycle endThe opposite of @PostConstruct is @PreDestroy: last instructions, run when the context closes. Use it to release resources. In plain Spring the context only closes if you call context.close() or use try-with-resources; Spring Boot closes it on shutdown for you. A main() that never closes the context never runs them.
crew/Dealer.java + Main.java
@Component
public class Dealer {
    @PostConstruct
    public void init()  { System.out.println("Dealer ready"); }

    @PreDestroy                     // runs on context.close(), for singletons only
    public void close() { System.out.println("Dealer leaving"); }
}

// try-with-resources closes the context, so @PreDestroy actually runs
try (var context = new AnnotationConfigApplicationContext(HeistPlan.class)) {
    Dealer p = context.getBean(Dealer.class);
}
XML configuration, the older wayBefore annotations, beans were declared in XML. You'll still meet it in older projects. Everything in this chapter has an XML equivalent; new code should use Java configuration.
src/main/resources/config.xml
<beans xmlns="http://www.springframework.org/schema/beans" ...>
    <bean id="dealer" class="org.example.crew.Dealer">
        <property name="name" value="Frank"/>    <!-- calls setName("Frank") -->
    </bean>
</beans>

// Main.java
var context = new ClassPathXmlApplicationContext("config.xml");
The full life of a bean

The memory simulator shows a bean being born. Here is the full sequence Spring runs for every singleton when the context starts:

  1. Read the recipes. Spring reads @Configuration classes and scanned packages and builds a BeanDefinition for each bean: a recipe, not an object.
  2. Instantiate. It calls the constructor. Constructor injection happens here.
  3. Populate. It fills @Autowired fields and setters.
  4. Aware callbacks. If the bean asked for its own name or the context (BeanNameAware, ApplicationContextAware), Spring tells it now. You'll rarely need these.
  5. Post-processors, before init. BeanPostProcessors can inspect or change the bean.
  6. Initialise. @PostConstruct, then afterPropertiesSet(), then any @Bean(initMethod = ...).
  7. Post-processors, after init. This is where proxies are made. If an aspect or @Transactional applies, the context stores the proxy, not your object. That's why chapters 6 and 13 behave the way they do.
  8. In service. Other beans get injected with it and call it.
  9. Destroy, when the context closes: @PreDestroy, then destroy(), then any destroyMethod. Prototype beans skip this step. Spring hands them over and forgets them.

BeanFactory vs ApplicationContext. BeanFactory is the basic container: it creates a bean only when someone asks for it. ApplicationContext extends it and adds eager singleton creation, events, profiles and the Environment, message sources, and automatic registration of post-processors. You'll always use ApplicationContext. BeanFactory is the free tier.

3
Ocean's Eleven

Wiring beans together

Linus can't start without Frank, and in the code a Pickpocket can't work without its Dealer. Spring offers five ways to wire them together. Most objects need other objects to do their job. Here a Pickpocket can't work without a Dealer. Connecting a bean to the beans it needs is called wiring, and Spring offers five ways to do it. In order:

Comic panel of Linus Caldwell and Frank Catton
Linus & FrankLinus (the Pickpocket) can't start until he's handed Frank (the Dealer). That hand-off is the wiring.

With @Bean methods

HeistPlan.java
// Version 1: calling the other @Bean method directly
@Bean
public Pickpocket pickpocket() {
    Pickpocket p = new Pickpocket();
    p.setDealer(dealer());   // does NOT create a second Dealer, see below
    return p;
}

// Version 2 (preferred): ask for it as a parameter
@Bean
public Pickpocket pickpocket(Dealer dealer) {
    Pickpocket p = new Pickpocket();
    p.setDealer(dealer);
    return p;
}
How version 1 worksSpring quietly subclasses every @Configuration class with a proxy. When pickpocket() calls dealer(), the proxy jumps in and hands back the bean that already exists. It's a polite lie, and it only works inside @Configuration. In a plain @Component, every call would build a brand-new Dealer, and two Franks would turn up at the same table.so you would end up with two separate Dealer objects instead of one shared bean.

With @Autowired on components

crew/Pickpocket.java
// Field injection: short, but the field can't be final and tests can't set it
@Autowired
private Dealer dealer;

// Constructor injection: the recommended way
private final Dealer dealer;

@Autowired                   // optional when the class has only one constructor
public Pickpocket(Dealer dealer) {
    this.dealer = dealer;
}

// Setter injection: for optional dependencies only
@Autowired
public void setDealer(Dealer dealer) {
    this.dealer = dealer;
}

Use constructor injection by default. A class with a single constructor is wired automatically, so the Spring Boot code in chapters 7–15 needs no @Autowired at all. Field injection mostly turns up in older code.

Choosing between two beans of the same type

HeistPlan.java
@Bean public Driver virgil() { return new Driver("Virgil Malloy"); }
@Bean public Driver turk()   { return new Driver("Turk Malloy"); }

@Bean
public Getaway getaway(@Qualifier("turk") Driver driver) { return new Getaway(driver); }

Without @Qualifier, Spring tries to match the parameter name to a bean name. If that fails too, startup fails with NoUniqueBeanDefinitionException, and nothing in your app is born at all.

Circular dependencies

If Linus needs Rusty and Rusty needs Linus through their constructors, Spring can't build either one. Two objects, each refusing to exist until the other does:

crew/Linus.java + crew/Rusty.java
@Component
public class Linus { public Linus(Rusty rusty) { } }   // waits for Rusty's signal

@Component
public class Rusty { public Rusty(Linus linus) { } }   // waits for Linus to move

// Startup fails with BeanCurrentlyInCreationException:
// "The dependencies of some of the beans in the application context form a cycle"
// Fix the design: move the shared step into a third bean (a Signal) that both depend on.

Spring Boot rejects circular references by default. Fix the design by moving the shared logic into a third bean. Don't paper over it with @Lazy. That doesn't end the relationship; it just delays the funeral.

4
The Princess Bride

Programming to abstractions

The crew obeys Roberts, never the particular man behind the mask. Good code separates what happens (interfaces) from how it happens (implementations). A class that depends only on interfaces doesn't care which class does the work, so you can swap implementations without changing it. Below, VoyageService knows only the interfaces and never learns which classes do the work:

Comic-style portrait of The Dread Pirate Roberts
The Dread Pirate RobertsThe interface. Whoever is under the mask is the implementation.
VoyageService→ShipLog←DBShipLog·Captain←Westley… / Ryan…

Step 1: no framework at all

main/Main.java
ShipLog shipLog = new DBShipLog();
Captain captain = new WestleyCaptain();
VoyageService voyageService = new VoyageService(shipLog, captain);

This works. It also makes Main personally responsible for every birth, in the right order, by hand. Forget one line and something is born without its dependencies, and it won't find out until it tries to use them.

Step 2: Spring does the wiring

implementations + service
@Repository  public class DBShipLog implements ShipLog { ... }
@Component   public class WestleyCaptain implements Captain { ... }

@Service
public class VoyageService {
    public VoyageService(ShipLog shipLog,
                          Captain captain) { ... }
}

The annotation goes on the implementation, never on the interface. Spring finds the single class that implements the interface and injects it. The same wiring can also be written with @Bean methods instead of scanning.

Step 3: two implementations

captains/*.java, ship/TrainingVoyage.java
// Option A: one implementation is the default everywhere
@Component @Primary
public class WestleyCaptain implements Captain { ... }

// Option B: label each one, and let each consumer choose
@Component @Qualifier("WESTLEY") public class WestleyCaptain ...
@Component @Qualifier("RYAN")  public class RyanCaptain  ...

public VoyageService(ShipLog repo,
                      @Qualifier("WESTLEY") Captain captain) { ... }
public TrainingVoyage(@Qualifier("RYAN") Captain captain) { ... }
Try it · The Princess Bride: will the ship sail?
Watch Spring succeed, or fail in great detail
Classes found by the scan
DBShipLog@Repository
WestleyCaptain@Component
VoyageService@Service
Application context (beans)
DBShipLogempty
westleyCaptainempty
voyageServiceempty
Your code
Main.main()wants a VoyageService

The stereotypes

AnnotationLayerExtra behaviour
@ComponentAnythingNone
@ServiceBusiness logicNone. It marks the class as business logic.
@RepositoryData accessMarks the class for exception translation: exceptions thrown out of its methods are converted to Spring's DataAccessException. This needs two things: a PersistenceExceptionTranslationPostProcessor (Spring Boot registers one, plain Spring doesn't) and a translator for your technology (JPA provides one). With JdbcTemplate, as in this guide, the template already translates SQLException itself.
@Controller / @RestControllerWebMakes the class a web controller. A method only handles requests when a mapping annotation (@GetMapping, @PostMapping, @RequestMapping…) connects it to a path. @RestController also adds @ResponseBody (chapters 7 and 10).
Reading the two startup errorsLearn these two faces. They turn up at every startup that dies:
ErrorCauseFix
NoSuchBeanDefinitionExceptionAn interface with no implementation bean: the class is missing an annotation, or sits outside the scanned package.Annotate the implementation, or move it under the main class's package.
NoUniqueBeanDefinitionExceptionTwo or more beans match and none is @Primary.@Primary for a default, or @Qualifier at the injection point.
5
The Prestige

Bean scopes and lifecycle

Angier's machine and the one stage manager are the two ideas in this chapter. A bean's scope decides how many instances Spring creates and how long each one lives. The default, singleton, means one instance per context, shared by everyone who asks. Prototype means a new instance every time you ask. Singletons can also be created at startup (eager) or on first use (lazy).

Comic-style portrait of Robert Angier
Robert AngierPrototype scope: a brand-new copy every night.
Comic-style portrait of Alfred Borden
Alfred BordenTwo men, one name: a singleton is one per bean definition, not one per class.

Singleton (the default), eager vs lazy

ProjectConfig.java / Main.java
@Bean
@Lazy                      // without @Lazy: built while the context starts (eager)
public Angier angier() { return new Angier(); }
Console output without @Lazy (eager)Console output with @Lazy
Angier instance created!
Before retrieving the bean
Before retrieving the bean
Angier instance created!

Eager is the safer default: a broken bean fails at startup, in front of you, instead of on the first real user's request, in front of your boss.

Prototype: a new object every time

ProjectConfig.java
@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Angier angier() { return new Angier(); }

Angier cs1 = context.getBean(Angier.class);
Angier cs2 = context.getBean(Angier.class);
System.out.println(cs1 == cs2);   // false
Try it · The Prestige: singleton, lazy or prototype
Start the context, then call getBean() a few times
Mainkeeps cs1, cs2, …
Application contextnot started
Angier objects in memoryeach one has its own id

The trap: a prototype inside a singleton

theatre/StageManager.java
// StageManager is a singleton, so a directly @Autowired Angier would be
// resolved only once and reused forever, defeating its prototype scope.
@Autowired
private ObjectFactory<Angier> angierFactory;

public Angier getAngier() {
    return angierFactory.getObject();   // fresh instance each call
}
The modern versionObjectFactory works, but it's the flip phone of lazy lookups. ObjectProvider extends it, works with constructor injection, and adds getIfAvailable() and getIfUnique().
StageManager.java
@Service
public class StageManager {

    private final ObjectProvider<Angier> angiers;

    public StageManager(ObjectProvider<Angier> angiers) {
        this.angiers = angiers;
    }

    public Angier next() {
        return angiers.getObject();
    }
}

Singletons are shared by every thread

Thread safety

In a web app, one singleton serves every request at the same time. Give it a mutable field and two threads will eventually write to it in the same instant. One of them loses, and nobody notices. Two safe patterns:

  • A list shared by every request uses a CopyOnWriteArrayList.
  • A counter shared by every request uses an AtomicInteger, like the all-day board in chapter 9.

The rule: keep singletons stateless (only final dependencies). If one must hold state, use thread-safe types. Or enjoy a bug that only shows up on Tuesdays, under load, never on your laptop.

ScopeInstancesSpring destroys it?Typical use
singletonOne per contextYes (@PreDestroy runs)Services, repositories, controllers
prototypeOne per request for the beanNo. Spring hands it over and walks away. No @PreDestroy, no funeral, just the garbage collector, eventuallyStateful helpers with short lives
request / session / applicationPer HTTP request / user session / servlet contextYesChapter 9
6
Cyrano de Bergerac

Aspects: code that wraps other code

Cyrano adds his words to everything Christian says, and Christian's own lines never change. An aspect does the same for your methods: it runs code around them without the methods knowing. An aspect is code that runs around your methods without the methods knowing. You write the extra logic once, and Spring applies it to every method you choose. Typical uses are logging, auditing, security checks, timing and transactions. To turn aspects on, add spring-aspects and put @EnableAspectJAutoProxy on the config.

Comic-style portrait of Cyrano
CyranoThe aspect. Every line passes through him first.
Comic-style portrait of Christian
ChristianThe target bean, wrapped by the proxy.
Comic-style portrait of Roxane
RoxaneThe caller. She only ever talks to the proxy.
A proxy and self-invocation in three panelsPanel 1: a call addressed to the bean is caught first by a masked stand-in, the proxy. Panel 2: the proxy adds extra behaviour to the call and passes it to the real bean. Panel 3: the bean calls its own method with this, the call never leaves the bean, and the proxy is skipped.THE CALL ARRIVESspeak()The proxy takes it firstADVICE ADDED+ @Aroundreal beanThen the real method runsTALKING TO ITSELFthis.compose()NO PROXY!The aspect never sees it
Every call from outside goes through the proxy; a call from the bean to itself never does.

Adding the aspects dependency

spring-context already contains Spring AOP, the proxy machinery. What it lacks is the AspectJ annotations (@Aspect, @Before, @Around) and the pointcut-expression parser. spring-aspects brings in AspectJ's weaver library, which provides both. Keep it on the same version as spring-context. Mixing Spring module versions is how you get NoSuchMethodError at startup.

pom.xml · inside <dependencies>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>7.0.8</version>   <!-- same as spring-context -->
</dependency>
A BOM keeps every Spring module on one version

Once you have two or more org.springframework artifacts, stop typing the version on each one. Import the Bill of Materials (BOM): a file that lists a matching version for every Spring module. Then each dependency is declared with no version, and one number controls them all. Spring Boot's parent (chapter 7) is this same idea, scaled up to hundreds of libraries.

pom.xml · with the Spring Framework BOM
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>7.0.8</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <!-- no versions: the BOM supplies them -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
    </dependency>
</dependencies>
Main→ calls →Proxy of Christian→ runs aspect →real Christian

From now on, context.getBean(Christian.class) returns a proxy: a body double. You think you're talking to Christian. You're talking to its agent, who runs the aspect first and then maybe lets you through.

The AOP vocabulary

Logging, auditing, security and transactions are cross-cutting concerns: they're needed in many classes but belong to none of them. Copy-pasting them into every method is how you end up with 400 identical log.info lines and one that's slightly wrong. AOP moves each concern into one place, and the vocabulary sounds worse than it is:

TermMeaningIn this chapter
AspectThe class holding the cross-cutting logicCyranoAspect, LeBretAspect
AdviceWhat to run, and when: before, after or aroundThe @Before and @Around methods
Join pointA point in execution where advice can run. In Spring AOP this is always a method call on a beanspeak(...) being called
PointcutThe expression choosing which join points get the adviceexecution(* balcony.*.*(..)), @annotation(Whispered)
TargetThe real object being wrappedChristian
WeavingConnecting aspects to targetsSpring does it at runtime, with proxies
anatomy of an execution pointcut
execution(  *           balcony.*     .*        (..)  )
            │           │              │         │
            return type package.Class  .method   any arguments
            (any)       (any class)    (any)     (zero or more)

Two kinds of proxy. In plain Spring, a bean that implements an interface gets a JDK dynamic proxy, which implements the same interface. A bean that doesn't gets a CGLIB proxy, which is a generated subclass. Spring Boot uses CGLIB by default. Either way, the proxy can only intercept calls that come in from outside. A final or private method can't be overridden, so its advice silently never runs. Spring AOP only intercepts method calls on beans. Full AspectJ can also weave into constructors and field access, at compile time or load time. You almost never need it.

Step 1: @Before with an execution pointcut

aspects/CyranoAspect.java
@Aspect
@Component
public class CyranoAspect {
    private static final Logger logger = LoggerFactory.getLogger(CyranoAspect.class);   // org.slf4j

    @Before("execution(* org.example.balcony.Christian.speak(..))")
    public void log(JoinPoint joinPoint) {
        logger.info("Method {} will execute with parameters {}",
            joinPoint.getSignature().getName(), Arrays.asList(joinPoint.getArgs()));
    }
}

Step 2: @Around can change arguments and return values

aspects/CyranoAspect.java
@Around("execution(* org.example.balcony.Christian.composeReply(..))")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] arguments = joinPoint.getArgs();
    arguments[0] = "A line worthy of Roxane";                          // change the input
    Object returnedValue = joinPoint.proceed(arguments);  // run the real method
    return returnedValue + " (polished)";                 // change the output
}
Watch outIf an @Around advice forgets to call proceed(), the real method never runs and the caller gets null. No error. No warning. No body.

Step 3: target methods with your own annotation

aspects/Whispered.java + CyranoAspect.java
@Retention(RetentionPolicy.RUNTIME)   // must survive to runtime, or Spring can't see it
@Target(ElementType.METHOD)
public @interface Whispered { }

@Around("@annotation(org.example.aspects.Whispered)")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable { ... }

// Christian
@Whispered public void speak(String line) { ... }
@Whispered public String composeReply(String text) { ... }

This is the grown-up pattern. The method opts in explicitly, instead of being targeted by a pointcut string that silently stops matching the day someone renames a package.

Step 4: two aspects on one method

aspects/LeBretAspect.java
@Aspect @Component @Order(1) public class CyranoAspect { ... }
@Aspect @Component @Order(2) public class LeBretAspect   { ... }

The lower @Order is the outer layer: first in, last out. Like a security guard who checks you in at the door and is still standing there, staring, when you leave.

CyranoAspect (Order 1) · "will execute with…"
LeBretAspect (Order 2) · "before method execution"
Christian.speak()
LeBretAspect · "after method execution"
CyranoAspect · "executed and returned…"
Try it · Cyrano: follow a line through the aspects
Cyrano is the outer aspect, Le Bret the inner one
Maincalls the bean
CyranoAspect@Order(1)
LeBretAspect@Order(2)
Christianthe real object
The other advice typesSo far you have used @Before and @Around. There are three more:
aspects/OutcomeAspect.java
@Aspect
@Component
public class OutcomeAspect {
    private static final Logger logger = LoggerFactory.getLogger(OutcomeAspect.class);   // org.slf4j

    // A named, reusable pointcut
    @Pointcut("@annotation(org.example.aspects.Whispered)")
    public void loggedMethods() { }

    // Only when the method returns normally; "result" is bound to the return value
    @AfterReturning(value = "loggedMethods()", returning = "result")
    public void success(JoinPoint jp, Object result) {
        logger.info("{} returned {}", jp.getSignature().getName(), result);
    }

    // Only when the method throws
    @AfterThrowing(value = "loggedMethods()", throwing = "ex")
    public void failure(JoinPoint jp, Exception ex) {
        logger.warn("{} failed: {}", jp.getSignature().getName(), ex.getMessage());
    }

    // Always, like a finally block
    @After("loggedMethods()")
    public void always(JoinPoint jp) {
        logger.info("{} finished", jp.getSignature().getName());
    }
}
Pointcut expressionMatches
execution(* org.example.balcony.*.*(..))Every method of every class in balcony
execution(public String *(..))Public methods returning String
@annotation(org.example.aspects.Whispered)Methods annotated with @Whispered
within(org.example.balcony..*)Anything in balcony or its sub-packages
bean(christian)The bean with that name
Proxy limits · these matter again in chapter 13
  • Self-invocation: if speak() calls this.composeReply(), the aspect does not run for the inner call, because this is the real object, not the proxy. Talking to yourself doesn't go through your agent.
  • Aspects only apply to beans. An object made with new has no proxy.
  • Private and final methods can't be intercepted.

In Spring Boot you don't need @EnableAspectJAutoProxy. Adding the AOP starter is enough, because Boot does your chores now. (The starter is spring-boot-starter-aspectj.)

Part 2 · chapters 7–11

Web apps with Spring Boot

Spring Boot 4.1.1 on Java 17. Everything from Part 1 still applies. Boot just does all the boring parts and takes none of the credit, which makes it the opposite of most group projects.

7
The Bear

Spring Boot and Spring MVC

Carmy's brigade gives every order one way into the kitchen and one station that handles it. Spring MVC does the same for HTTP: Spring MVC turns HTTP requests into calls to your Java methods. Tomcat receives the request, DispatcherServlet routes it to one controller method, and the result goes back as a page or as JSON. Spring Boot sets all of that up from a single main class:

Comic-style portrait of Carmy
CarmyDispatcherServlet: every order goes through one point.
Comic-style portrait of Sydney
SydneyPre-orders left on: every worker thread is taken.
TheBeefApplication.java
@SpringBootApplication
public class TheBeefApplication {
    public static void main(String[] args) {
        SpringApplication.run(TheBeefApplication.class, args);
    }
}

@SpringBootApplication is three annotations in one:

  • @Configuration: the class can hold @Bean methods.
  • @ComponentScan: scans this package and everything below it, which is why every class lives under com.example.thebeef.
  • @EnableAutoConfiguration: creates beans based on what's on the classpath. Add the JDBC starter and a DataSource and a JdbcTemplate appear.

Starters such as spring-boot-starter-webmvc bundle a feature's dependencies at compatible versions. The spring-boot-starter-parent pins every version, which is why the pom.xml has no version numbers.

Creating a Spring Boot project

The book creates its Boot projects with the Spring Initializr, at start.spring.io or through the IDE's "New Spring Boot project" wizard, which calls the same service. You don't write the build file by hand; you fill in a form:

  1. Project: Maven or Gradle (Groovy or Kotlin). This choice only changes the build file. The Java code is identical either way.
  2. Language Java, and a Spring Boot version. Avoid SNAPSHOT and M (milestone) versions.
  3. Metadata: group (com.example), artifact (the-beef), Java version (17).
  4. Dependencies: search and add Spring Web. Every later chapter adds one more starter here, or in the build file directly.
  5. Generate, unzip, open the folder in your IDE.
Generated fileWhat it's for
pom.xml or build.gradleThe parent/plugins, your starters, the Boot build plugin
mvnw / gradlew + wrapper folderDownloads the right Maven or Gradle version on first run, so nobody has to install one
…Application.javaThe @SpringBootApplication main class shown above
src/main/resources/application.propertiesConfiguration (chapter 7 onward)
src/main/resources/static, templatesPlain files served as-is / templates for the view engine
…ApplicationTests.javaOne test that checks the context starts (chapter 15)
pom.xml · the chapter 7 project
<project ...>
    <modelVersion>4.0.0</modelVersion>

    <!-- 1. The parent: pins a tested version for every library Boot knows -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.1</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>the-beef</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <!-- 2. Starters: no <version>, the parent supplies it -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 3. Builds the runnable jar and adds ./mvnw spring-boot:run -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
The three pieces of every Boot build file
  1. Version management. Maven's spring-boot-starter-parent and Gradle's io.spring.dependency-management plugin both import Boot's BOM: hundreds of libraries (Tomcat, Jackson, Hikari, JDBC drivers, JUnit) at versions tested together. That's why you write no versions, and why upgrading Boot upgrades everything in one move. Gradle can also do it without the plugin: implementation platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES).
  2. Starters. A starter is an almost-empty jar whose only content is a list of dependencies. spring-boot-starter-webmvc pulls in Spring MVC, embedded Tomcat, Jackson, logging and Boot's auto-configuration. Auto-configuration then sees those classes on the classpath and creates the beans. Adding a starter is how you switch a feature on.
  3. The Boot build plugin. It repackages your app into one "fat" jar with every dependency inside, so java -jar app.jar just works. It also adds the run command: ./mvnw spring-boot:run or ./gradlew bootRun.
How the web actually works

A web app is a server that waits for clients (browsers, phones, other servers) and answers them over HTTP. HTTP is plain text with a strict shape: the client sends a request and gets exactly one response back.

an HTTP request and its response
GET /products?name=coffee HTTP/1.1        ← method, path, query string
Host: localhost:8080                      ← headers: metadata about the request
Accept: text/html
                                          ← blank line; a body would follow (POST/PUT)

HTTP/1.1 200 OK                           ← status code
Content-Type: text/html                   ← headers about the response

<html>...the page...</html>              ← body
  • The servlet container. Java web apps don't speak HTTP themselves. A servlet container (Tomcat, embedded by Spring Boot) listens on the port, parses the text into an HttpServletRequest object and hands it to a servlet. Spring registers exactly one servlet, DispatcherServlet. This is the front controller pattern: one entry point routes every request to the right controller.
  • One thread per request. Tomcat serves each request on a thread from its pool (200 by default). Two users at once means two threads running through the same singleton controller at the same moment. That's the chapter 5 thread-safety rule, now with real traffic.
  • HTTP is stateless. Each request arrives with no memory of the previous one. "Logged in" and "items in my cart" are faked on top with cookies and sessions (chapter 9).
  • Two styles of answer. Server-side rendering builds the HTML on the server (chapters 7–9, Thymeleaf). A REST API returns data, usually JSON, and lets the client draw the page (chapter 10).

Inside Tomcat: from click to response

The theory box above describes the trip. The simulator below shows it happening. Send, step by step follows a single request through every hop, and the two panels show the same request as raw bytes on the wire and as Java objects inside Tomcat. Then switch the controller to slow and press Flood: ten users, four threads, and you'll see exactly how a web server dies of politeness.

Try it · The Bear: inside Tomcat, from order to plate
Every hop, in order. Then flood it and watch the threads run out.
Browserthe client
NetworkTCP · localhost:8080
ConnectorNIO · Acceptor + Poller
Http11Processorbytes ⇄ objects
Worker threadsmaxThreads = 4 here (200 by default)
Connectionclosed
Thymeleaf / Jacksonwrites the body
Controlleryour code
DispatcherServletSpring's front door
Filter chainruns before Spring MVC
On the wire · bytes
Nothing sent yet.
Inside Tomcat · Java objects
Nothing parsed yet.
Spring Boot propertyDefaultWhat it controls in the simulator
server.tomcat.threads.max200The worker threads (4 above)
server.tomcat.max-connections8192How many connections Tomcat holds open at once, including the ones waiting for a thread
server.tomcat.accept-count100The operating system's queue once max-connections is reached. Past that, connections are refused
server.tomcat.connection-timeoutTomcat's own (60 s embedded)How long Tomcat waits for the request bytes to arrive
server.tomcat.keep-alive-timeoutsame as connection-timeoutHow long an idle keep-alive connection stays open (sped up to 20 s above)
The lesson of the floodA thread waiting on a slow call isn't working. It's on hold, and it still counts against your 200. Fill them all and every other user waits, including the ones whose requests would take a millisecond. This is why chapter 11 insists on timeouts.

What happens on a request

Browser→Tomcat→DispatcherServlet→Handler mapping→Your controller→View resolver→HTML
Try it · The Bear: send an order through Spring MVC
The controllers from chapters 7–10
Browserthe client
Tomcatembedded server
DispatcherServletfront controller
HandlerMappingfinds the method
Controlleryour code
Thymeleafrenders templates/
ControllerAdvicemaps exceptions
JacksonJSON ⇄ objects
PaymentServicebusiness logic
No request sent yet
controllers/MenuController.java
@Controller
public class MenuController {
    @RequestMapping("/menu")
    public String menu() {
        return "menu.html";    // a view name, not text: Spring looks up the page
    }
}

Before Thymeleaf is added, menu.html lives in static/. Afterwards it moves to templates/. static/ is served unchanged; templates/ is processed by the template engine.

Configuration files

A project can have both application.properties and application.yml. Spring merges them, and if both define the same key, .properties wins. In a real project, pick one format.

Your app.* settings are never read

application.yml defines app.greeting and app.timeout-seconds, but no code reads them yet. The type-safe way to read a group of settings is @ConfigurationProperties:

config/AppProperties.java
// Binds every app.* key. Relaxed binding maps "timeout-seconds" to timeoutSeconds.
@ConfigurationProperties(prefix = "app")
public record AppProperties(String greeting, int timeoutSeconds, String owner) { }

// On the application class, so Spring finds and registers it:
@SpringBootApplication
@ConfigurationPropertiesScan
public class TheBeefApplication { ... }

// Then inject it like any bean:
public MenuController(AppProperties appProperties) { ... }

Prefer this to scattering @Value("${...}") across classes. A typo in a @Value key only fails at runtime, usually in production, usually at night. A properties record keeps every setting in one typed place.

8
The Bear

Dynamic views and request data

Every ticket carries the details of the order: the table number, the extras, sometimes a whole form. A request often carries data: an id in the path, filters in the query string, or the fields of a submitted form. This chapter is about reading that data from a request (path variables, query parameters and form fields) and sending data back to the page through the Model.

Thymeleaf in one table

A Thymeleaf template is normal HTML with th: attributes. At render time, Thymeleaf replaces them with values from the Model. The file still opens in a browser as plain HTML, which is the whole point.

SyntaxMeaningExample
${...}A value from the Modelth:text="${username}"
*{...}A field of the object chosen with th:objectth:field="*{name}"
@{...}A URL, with the context path added for youth:action="@{/products}"
th:eachRepeat the element for each item<tr th:each="p : ${products}">
th:if / th:unlessShow the element only when true / falseth:if="${products.isEmpty()}"

th:text escapes HTML, so a dish called <script> shows up as text instead of running. th:utext doesn't escape. Only use it on content you wrote yourself, never on user input.

Adding Thymeleaf

One starter switches on the template engine. Boot then configures a view resolver that looks in src/main/resources/templates/, which is why menu.html had to move there.

pom.xml · inside <dependencies>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Sending data to the page with Model

MenuController.java
@RequestMapping("/menu")
public String menu(Model page) {
    page.addAttribute("chef", "Carmy");
    page.addAttribute("dishes", List.of(new Dish("Italian beef", 14.0), ...));
    return "menu.html";
}
templates/menu.html
<h1>Chef on the pass: <span th:text="${chef}"></span></h1>
<tr th:each="dish : ${dishes}">
    <td th:text="${dish.name}"></td>
    <td th:text="${dish.price}"></td>
</tr>

Reading data from the request

MenuController.java
// Query parameter:  GET /menu?extras=giardiniera
@RequestMapping("/menu")
public String menu(@RequestParam String extras, Model page) { ... }

// Path variable:    GET /menu/7
@RequestMapping("/menu/{table}")
public String menu(@PathVariable int table, Model page) { ... }
UseForExample
@PathVariableIdentifying a resource; the value is required/tables/7
@RequestParamOptional filters, sorting, paging/dishes?name=beef

A @RequestParam is required by default. Forget it and you get a 400, which is Spring for “you had one job”. Use required = false as in MainController's logout, or a defaultValue as in TransferController.

GET shows the form, POST receives it

DishesController.java
@GetMapping("/dishes")
public String viewDishes(Model model) { ... }

@PostMapping("/dishes")
public String addDish(@RequestParam String name, @RequestParam double price, Model model) {
    Dish d = new Dish(name, price);
    dishService.addDish(d);
    model.addAttribute("dishes", dishService.findAll());
    return "dishes.html";
}
Bug · refresh re-submits the formAfter a POST, DishesController renders the page directly. Press F5 and the browser re-sends the form, so the dish is added again. Press it five times and you've built an inventory system for duplicates. The fix is the Post/Redirect/Get pattern.
DishesController.java
@PostMapping("/dishes")
public String addDish(@ModelAttribute Dish dish) {   // binds name + price fields
    dishService.addDish(dish);
    return "redirect:/dishes";    // browser follows with a GET; refresh is now harmless
}

@ModelAttribute fills an object from the form fields by name, so you no longer need one @RequestParam per field. DoorController already redirects after login; do the same after every form POST.

9
The Bear

Web scopes: request, session, application

A ticket lasts for one order, a tab for one table's visit, and the all-day board for the whole service. In a web app, some data should live only for one request, some for one user's visit, and some for the whole app. Web scopes give beans three lifetimes: one HTTP request, one user's session, or the whole application.

ScopeYour beanLives for
@RequestScopeTicketProcessor: holds the submitted username and passwordOne HTTP request
@SessionScopeTableTab: remembers who is logged inOne user's session (a cookie)
@ApplicationScopeAllDayBoard: counts all loginsThe whole app, shared by all users
Try it · The Bear: two diners, three scopes
Natalie and Bob use the same app at the same time
Browser A · Natalielogin page
Server: one running app
AllDayBoard · @ApplicationScopecount = 0
Session A · @SessionScopeno session yet
Session B · @SessionScopeno session yet
@RequestScope beansexist only during a request
Browser B · Boblogin page
kitchen/TicketProcessor.java
@Component
@RequestScope
public class TicketProcessor {
    private final TableTab tableTab;   // session-scoped
    private final AllDayBoard allDayBoard;                       // application-scoped

    public boolean login() {
        allDayBoard.increment();
        boolean loginResult = "natalie".equals(username) && "password".equals(password);
        if (loginResult) {
            tableTab.setUsername(username);
        }
        return loginResult;
    }
}
How a singleton can hold a request-scoped beanDoorController is a singleton, born at startup, before any request exists. So what does it get injected with, a request from the future? No: a scoped proxy. @RequestScope and @SessionScope make Spring inject a stand-in object that, on every call, looks up the real instance for the current request or session. It's the same proxy idea as chapters 3, 6 and 13.

server.servlet.session.tracking-modes=cookie stops Tomcat from putting the session id in URLs (;jsessionid=...), where it could leak through logs and links. Session ids in URLs are how people end up logged in as a stranger after clicking a link pasted in a group chat.

A session expires after 30 minutes without a request. Change it with server.servlet.session.timeout=15m. Every session-scoped bean dies with its session.

Fine for learning. A crime in production.
  • The password is "password", hard-coded in Java and compared as plain text. Natalie's account is protected by the honour system. Part 5B replaces this whole login flow with Spring Security.
  • Logging out with GET /main?logout means any link or image on any website can log Natalie out. Logout should be a POST.
  • Session data lives in one server's memory. Put two instances behind a load balancer and users get "logged out" whenever their next request lands on the other server. Users love that. Spring Session with Redis or JDBC fixes it.
  • The application-scoped login counter resets on every restart. It's less a statistic and more a mood.
10
Memento

REST endpoints

Leonard's notes have to carry everything, because he remembers nothing between scenes. A REST endpoint works by the same rule: every request brings everything the server needs, and the answer is data, not a page. A REST endpoint returns data, usually JSON, instead of an HTML page. Every request carries everything the server needs, because the server keeps no memory between requests. @RestController = @Controller + @ResponseBody: you return an object and Jackson turns it into JSON.

Comic-style portrait of Leonard Shelby
Leonard ShelbyStateless: every request carries its own notes.
Dependencies · nothing newChapters 9 and 10 need no new dependency. Jackson, the JSON library, already arrives with the web starter from chapter 7 (spring-boot-starter-webmvc, or spring-boot-starter-web in the book). Thymeleaf isn't needed for REST endpoints, but it's harmless to keep it.
NoteController.java
@GetMapping("/notes/teddy")
public Note teddy() { return Note.of("Teddy", "Do not believe his lies"); }    // 200 + JSON

@GetMapping("/notes/teddy/entity")
public ResponseEntity<Note> teddyEntity() {                 // full control
    return ResponseEntity
        .status(HttpStatus.ACCEPTED)
        .header("written-by", "Leonard")
        .body(Note.of("Teddy", "Do not believe his lies"));
}
What REST actually means

REST is a style for designing HTTP APIs. URLs name resources (nouns: /accounts/42), HTTP methods are the verbs, the body carries a representation (JSON), and every request is stateless: it carries everything the server needs. POST /deleteEverything is not REST. It's a confession.

MethodMeaningSafeIdempotentTypical success
GETReadYesYes200
POSTCreate, or trigger an actionNoNo201 (or 200)
PUTReplace the whole resourceNoYes200 or 204
PATCHChange part of itNoNot guaranteed200 or 204
DELETERemove itNoYes204

Safe means it changes nothing on the server. Idempotent means sending it twice has the same effect as sending it once, so a client can retry after a timeout without fear. That's why the double-submit bug in chapter 8 only happens with POST.

How objects turn into JSON. Spring uses HTTP message converters. For @RequestBody, it reads the Content-Type header, picks the matching converter (Jackson for JSON), and turns the body into your record. For the return value, it checks the client's Accept header and serialises the object back. If the client sends a type nobody can read, the answer is 415 Unsupported Media Type. If it asks for a type nobody can write, the answer is 406 Not Acceptable. Jackson reads records through their accessor methods, which is why records need no getters.

Receiving JSON and handling errors in one place

PaymentController + ExceptionControllerAdvice
@PostMapping("/payment")
public ResponseEntity<Payment> makePayment(@RequestBody Payment payment) {   // JSON → record
    Payment processed = paymentService.processPayment(payment);   // may throw
    return ResponseEntity.status(HttpStatus.ACCEPTED)
        .header("requestId", UUID.randomUUID().toString())
        .body(processed);
}

@RestControllerAdvice                       // applies to every controller
public class ExceptionControllerAdvice {
    @ExceptionHandler(NotEnoughMoneyException.class)
    public ResponseEntity<ErrorDetails> notEnoughMoney(NotEnoughMoneyException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorDetails(e.getMessage()));
    }
}

The service throws a domain exception and doesn't know about HTTP. The advice translates it into a status code. Keep that separation. A service that knows HTTP status codes has been reading things it shouldn't.

To watch the exception path, send both payment requests in the request simulator in chapter 7.

Picking the status code

CodeMeansUse for
200 OKDone, here is the resultMost GET and synchronous POST calls
201 CreatedA new resource existsPOST /tickets, with @ResponseStatus(HttpStatus.CREATED)
202 AcceptedReceived, will be processed laterAsync jobs. Return 202 only when the work really happens later; a payment that is already finished should get 200.
204 No ContentDone, nothing to returnDELETE, or POST /transfer
400 / 404 / 409Bad input / not found / conflictValidation errors, missing ids, duplicates
Reading headers, and the standard error formatSpring ships ProblemDetail, the standard JSON error format (RFC 9457). It replaces a hand-made error record like ErrorDetails.
ExceptionControllerAdvice.java
// Reading a request header
@GetMapping("/whoami")
public String whoAmI(@RequestHeader("User-Agent") String userAgent) { return userAgent; }

// Standard error body: {"type":"about:blank","title":"Not enough money","status":400,"detail":"..."}
@ExceptionHandler(NotEnoughMoneyException.class)
public ProblemDetail notEnoughMoney(NotEnoughMoneyException e) {
    ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, e.getMessage());
    problem.setTitle("Not enough money");
    return problem;
}

// A catch-all, so unexpected errors never leak a stack trace to the client
@ExceptionHandler(Exception.class)
public ProblemDetail unexpected(Exception e) {
    log.error("Unhandled error", e);           // full detail in the server log only
    return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
}
AccountNotFoundException.java + AccountController.java
// The shortest mapping: the exception itself declares its status
@ResponseStatus(HttpStatus.NOT_FOUND)
public class AccountNotFoundException extends RuntimeException {
    public AccountNotFoundException(long id) { super("No account " + id); }
}

// 201 Created with a Location header: the REST way to answer "created"
@PostMapping("/accounts")
public ResponseEntity<Account> create(@RequestBody Account account) {
    Account saved = accountRepository.save(account);
    return ResponseEntity.created(URI.create("/accounts/" + saved.id())).body(saved);
}
11
Memento

Calling other REST services

Leonard depends on calls and notes from other people, and he can't control how long they take. Calling another service from your app carries the same risk. Apps often call other services over HTTP, and you can't control how long those services take to answer. Below, the same POST /payment endpoint is called three different ways. In all three the app calls itself at localhost:8080, which is fine for learning: the client code is the same whether the other service is local or remote.

proxy/PaymentsProxy.java · OpenFeign
@FeignClient(name = "payments", url = "${payments.url}")
public interface PaymentsProxy {
    @PostMapping("/payment")
    Payment createPayment(@RequestBody Payment payment);
}
// plus @EnableFeignClients(basePackages = "...proxy") and the spring-cloud BOM in the pom
proxy/PaymentsWebClientProxy.java · WebClient
public Mono<Payment> createPayment(Payment payment) {
    return webClient.post()
        .uri(paymentsUrl + "/payment")
        .bodyValue(payment)
        .retrieve()
        .bodyToMono(Payment.class);     // nothing is sent until something subscribes
}
proxy/PaymentsHttpClient.java + config/HttpClientConfig.java · HTTP interface
@HttpExchange("/payment")
public interface PaymentsHttpClient {
    @PostExchange
    Payment createPayment(@RequestBody Payment payment);
}

@Bean
public PaymentsHttpClient paymentsHttpClient(@Value("${payments.url}") String paymentsUrl) {
    RestClient restClient = RestClient.builder().baseUrl(paymentsUrl).build();
    HttpServiceProxyFactory factory = HttpServiceProxyFactory
        .builderFor(RestClientAdapter.create(restClient)).build();
    return factory.createClient(PaymentsHttpClient.class);
}

Dependencies for each client

The three clients come from three different places, and the build file shows it. OpenFeign is a Spring Cloud project, which has its own release train (named by year, such as 2025.1.x) and its own BOM. Import that BOM next to Boot's, and choose the train that matches your Boot version (start.spring.io does this for you). WebClient needs its starter. The HTTP interface and RestClient are part of Spring Framework, so the web starter already has them.

pom.xml · OpenFeign + WebClient
<properties>
    <java.version>17</java.version>
    <spring-cloud.version>2025.1.3</spring-cloud.version>   <!-- must match the Boot version -->
</properties>

<!-- Spring Cloud's BOM: versions for every Spring Cloud module -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <!-- 11.1 OpenFeign (plus @EnableFeignClients on a config class) -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <!-- 11.3 WebClient -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webclient</artifactId>
    </dependency>
    <!-- RestTemplate / RestClient / HTTP interfaces: nothing to add -->
</dependencies>

The book's second client is RestTemplate (11.2), which needs no dependency either. It's now in maintenance, and RestClient is its modern replacement with the same blocking style. Here is the book's version:

proxy/PaymentsRestTemplateProxy.java · book 11.2
@Component
public class PaymentsRestTemplateProxy {

    private final RestTemplate restTemplate;
    private final String paymentsUrl;

    public PaymentsRestTemplateProxy(RestTemplate restTemplate,
                                     @Value("${payments.url}") String paymentsUrl) {
        this.restTemplate = restTemplate;
        this.paymentsUrl = paymentsUrl;
    }

    public Payment createPayment(Payment payment) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("requestId", UUID.randomUUID().toString());
        HttpEntity<Payment> request = new HttpEntity<>(payment, headers);

        ResponseEntity<Payment> response = restTemplate.exchange(
            paymentsUrl + "/payment", HttpMethod.POST, request, Payment.class);
        return response.getBody();
    }
}

// RestTemplate is not created for you: declare the bean yourself
@Bean
public RestTemplate restTemplate() { return new RestTemplate(); }
AspectOpenFeignWebClientHTTP interface + RestClient
Comes fromSpring Cloud (extra BOM)Spring WebFluxSpring Framework itself
StyleInterfaceFluent, reactiveInterface
Blocking?YesNo (returns Mono/Flux)Yes (or reactive with a WebClient adapter)
StatusMaintenance modeActive, for reactive appsActive, the recommended default
RecommendationPick one. Three HTTP clients in one app is a collection, not an architecture. In a Spring MVC app like yours, use HTTP interfaces backed by RestClient. That needs no Spring Cloud dependency and no reactive types. Use WebClient only if the whole app is reactive (WebFlux). Spring Framework 7, which Boot 4 uses, can also register HTTP interfaces for you with @ImportHttpServices, so you can drop the factory code in HttpClientConfig.
Timeouts and remote errorsNone of the three clients above sets a timeout. If the payments service hangs, every request thread waits with it, and the server eventually runs out of threads. Always set a connect timeout and a read timeout, and decide what a 4xx or 5xx from the other side means for you.
config/HttpClientConfig.java
@Bean
RestClient paymentsRestClient(RestClient.Builder builder, @Value("${payments.url}") String url) {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setConnectTimeout(Duration.ofSeconds(2));   // can't reach the server
    requestFactory.setReadTimeout(Duration.ofSeconds(5));      // server too slow to answer
    return builder.baseUrl(url).requestFactory(requestFactory).build();
}

// Using RestClient directly, with explicit error handling
public Payment createPayment(Payment payment) {
    return paymentsRestClient.post()
        .uri("/payment")
        .body(payment)
        .retrieve()
        .onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
            throw new PaymentRejectedException(response.getStatusCode());
        })
        .body(Payment.class);
}
Part 3 · chapters 12–14 · PostgreSQL

Working with a database

From hand-written SQL with JdbcTemplate, through transactions, to repositories Spring writes for you. Also: the part where money starts disappearing.

12
The Bear

Data sources and JdbcTemplate

Repository→JdbcTemplate→DataSource (HikariCP pool)→PostgreSQL driver→Database

The kitchen works because pans are shared and always come back. Database connections work the same way. Opening a database connection is slow, so apps keep a set of open connections and reuse them. A DataSource hands out connections, and HikariCP keeps a pool of open ones so each query doesn't pay the cost of opening a new connection. JdbcTemplate borrows a connection, runs the SQL and always gives it back.

A connection pool under load in three panelsPanel 1: a rack holds three pans, the pool of three connections that are opened once and reused. Panel 2: three cooks each hold a pan while a fourth waits with ticket Q4. Panel 3: after five seconds the fourth cook gives up with a timeout.THE RACK: 3 PANSOpened once, then reusedHikariCP pool, max 3RUSH: 3 BUSY, 1 WAITINGQ4Q4 waits for a free pan5 SECONDS LATERQ4TIMEOUT!connection-timeout fires
A fixed number of connections, borrowed and returned. When all are busy, the next query waits, then times out.
repositories/TicketRepository.java
public void storeTicket(Ticket ticket) {
    String sql = "INSERT INTO ticket (dish, price) VALUES (?, ?)";
    jdbcTemplate.update(sql, ticket.dish(), ticket.price());   // ? = safe parameters
}

public List<Ticket> findAllTickets() {
    String sql = "SELECT id, dish, price FROM ticket ORDER BY id";
    return jdbcTemplate.query(sql, (resultSet, rowNumber) -> new Ticket(
        resultSet.getInt("id"),
        resultSet.getString("dish"),
        resultSet.getBigDecimal("price")));
}
Never build SQL with +"... WHERE name = '" + name + "'" is how you meet Little Bobby Tables. Always use ? or named parameters. Every example in this guide does.
What JdbcTemplate is hiding from you

Under every Java database call is JDBC, the standard API. The Postgres driver implements it and speaks Postgres's network protocol. A DataSource hands out connections, and the pool (Hikari) keeps them open. Opening a real connection costs a network round trip plus authentication, and you don't want to pay that on every query. Here's one query in raw JDBC:

raw JDBC: what life was like before
String sql = "SELECT id, name, amount FROM account WHERE id = ?";
try (Connection con = dataSource.getConnection();          // borrow from the pool
     PreparedStatement ps = con.prepareStatement(sql)) {
    ps.setLong(1, id);                                      // bind the ? safely
    try (ResultSet rs = ps.executeQuery()) {                // a cursor over the rows
        if (rs.next()) {
            return new Account(rs.getLong("id"), rs.getString("name"), rs.getBigDecimal("amount"));
        }
        return null;
    }
} catch (SQLException e) {                                  // checked, so you must catch it
    throw new RuntimeException(e);
}                                                           // close() returns the connection to the pool
the same query with JdbcTemplate
return jdbcTemplate.queryForObject(
    "SELECT id, name, amount FROM account WHERE id = ?",
    (rs, rowNum) -> new Account(rs.getLong("id"), rs.getString("name"), rs.getBigDecimal("amount")),
    id);

The lambda is a RowMapper: one row in, one object out. JdbcTemplate does everything else. It borrows and returns the connection, binds the parameters, loops over the rows and closes the resources. It also translates the checked SQLException into Spring's unchecked DataAccessException family (DuplicateKeyException, EmptyResultDataAccessException, and so on). Those are runtime exceptions, so they roll back transactions in chapter 13 without any extra configuration.

Dependencies: the JDBC starter and a driver

You always need two things: spring-boot-starter-jdbc (which brings JdbcTemplate, HikariCP and the auto-configuration) and the driver for your database. The book starts with an in-memory H2 database, so the examples run with no installation, then switches to MySQL. This repo uses PostgreSQL. Changing databases means swapping one driver line and the URL. The Java code stays the same.

pom.xml · inside <dependencies>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- the driver: pick ONE. runtime scope, because your code only uses JDBC interfaces -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- book, first:  com.h2database:h2          (in-memory, nothing to install) -->
<!-- book, later:  com.mysql:mysql-connector-j -->

No versions here either: Boot's BOM manages the drivers too. With H2 on the classpath and no spring.datasource.url, Boot creates an in-memory database by itself, which is how the book's first examples run with zero configuration.

Two ways to configure the DataSource

application.properties · Boot builds it
spring.datasource.url=jdbc:postgresql://localhost:5432/the_beef
spring.config.import=optional:file:./application-local.properties   # username + password, git-ignored
spring.datasource.hikari.maximum-pool-size=5
spring.datasource.hikari.connection-timeout=10000
spring.sql.init.mode=always                                          # run schema.sql on startup
config/DataSourceConfig.java · you build it
@Bean
public DataSource dataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl(url);
    dataSource.setMaximumPoolSize(3);
    return dataSource;     // Boot sees a DataSource exists and "backs off"
}
Two configurations, one winnerIf application.properties sets up the pool and a DataSourceConfig class also defines a DataSource bean, Boot silently ignores every one of those properties. The pool is CustomRackPool with 3 connections, not KitchenPool with 5. Keep one approach. For production, prefer the properties version and delete the class unless you need something only Java can do.
Try it · The Bear: the pan rack under load
Send six queries to three connections. Root for the fourth one.
Threads waiting for a connectionconnection-timeout = 5 s
HikariCP poolmax 3
PostgreSQLthe_beef

Your choices of BigDecimal in Java and NUMERIC(10,2) in SQL for money are correct, and nobody can take that away from you. double can't represent 0.10 exactly, and banks tend to notice.

JdbcClient, the modern APIJdbcTemplate is fine, in the way a fax machine is fine. JdbcClient is its fluent sibling: one fluent API for ? and :named parameters that can map rows to records automatically. Boot auto-configures it next to JdbcTemplate.
repositories/TicketRepository.java
@Repository
public class TicketRepository {
    private final JdbcClient jdbcClient;

    public TicketRepository(JdbcClient jdbcClient) { this.jdbcClient = jdbcClient; }

    public void storeTicket(Ticket ticket) {
        jdbcClient.sql("INSERT INTO ticket (dish, price) VALUES (:dish, :price)")
            .param("dish", ticket.dish())
            .param("price", ticket.price())
            .update();
    }

    public List<Ticket> findAllTickets() {
        return jdbcClient.sql("SELECT id, dish, price FROM ticket ORDER BY id")
            .query(Ticket.class)      // maps columns to record components by name
            .list();
    }

    public Optional<Ticket> findById(int id) {
        return jdbcClient.sql("SELECT id, dish, price FROM ticket WHERE id = :id")
            .param("id", id)
            .query(Ticket.class)
            .optional();
    }
}
13
Edge of Tomorrow

Transactions

Cage's day either reaches sundown or resets completely; there is no half-finished version. A money transfer needs the same guarantee. Some changes must happen completely or not at all, like a money transfer. It is two updates: take money from one account, add it to another. If the app fails between them, money disappears. A transaction groups the updates so they all succeed together, or none of them happen.

Comic-style portrait of Major William Cage
Major William CageRollback: he dies, and the day resets.
Comic-style portrait of Rita Vrataski
Rita VrataskirollbackFor: she resets the day on purpose.
A rollback in three panelsPanel 1: at the start of the transaction 100 moves from Cage to Rita and Cage drops to 900, uncommitted. Panel 2: an exception is thrown after the debit. Panel 3: the transaction rolls back and both accounts are 1000 again.6:00 AM · BEGINCAGE900RITA1000100Debit written, not committedNOON · SOMETHING THROWSCAGE900RITA1000BOOM!NEXT MORNING · ROLLBACKCAGE1000RITA1000As if it never happened
Rollback: the day resets, and the database goes back to how it was at the start of the transaction.
model/Account.java + repositories/AccountRepository.java
public record Account(@Id Long id, String name, BigDecimal amount) { }

public interface AccountRepository extends CrudRepository<Account, Long> {
    @Modifying
    @Query("UPDATE account SET amount = :amount WHERE id = :id")
    void changeAmount(@Param("id") long id, @Param("amount") BigDecimal amount);
}
services/TransferService.java
@Transactional
public void transferMoney(long senderId, long receiverId, BigDecimal amount, boolean failAfterDebit) {
    doTransfer(senderId, receiverId, amount, failAfterDebit);
}

private void doTransfer(...) {
    accountRepository.changeAmount(senderId, sender.amount().subtract(amount));
    if (failAfterDebit) throw new IllegalStateException("Simulated failure after debiting the sender");
    accountRepository.changeAmount(receiverId, receiver.amount().add(amount));
}
Controller→Transaction proxy: begin→transferMoney()→return → commit · throw → rollback

This is chapter 6 again: @Transactional is an @Around aspect that Spring ships for you. Every self-invocation and proxy rule from chapter 6 applies. Try it on the /transfer endpoint with ?failAfterDebit=true, once with ?transactional=false and once without.

Try it · Edge of Tomorrow: move money between Cage and Rita
TransferService, with a switch to fail halfway
TransferControllerPOST /transfer
Transaction proxy@Transactional
TransferServicedoTransfer()
PostgreSQL · accountcommitted data
1 · William Cage1000.00
2 · Rita Vrataski1000.00
Money in the bank2000.00
ACID, isolation and how @Transactional works
LetterPromiseIn the transfer
AtomicityAll the statements succeed, or none take effectDebit and credit happen together, or not at all
ConsistencyConstraints hold before and afterNo negative balance, if a constraint enforces it (mine doesn't)
IsolationConcurrent transactions don't see each other's half-finished workThe race simulator shows what happens when this isn't enough
DurabilityOnce committed, the data survives a crashThe database writes it to disk before saying OK

Isolation levels trade safety for speed. Each one blocks more of the classic anomalies:

LevelDirty readNon-repeatable readPhantom read
READ_UNCOMMITTEDpossiblepossiblepossible
READ_COMMITTED (Postgres default)nopossiblepossible
REPEATABLE_READ (MySQL default)nonopossible in the standard, not in Postgres
SERIALIZABLEnonono

The table shows the minimum the SQL standard requires, and a database may do better. Postgres runs REPEATABLE_READ on a snapshot taken at the transaction's first query, so phantom reads can't happen there. A dirty read sees data another transaction hasn't committed yet. A non-repeatable read reads the same row twice and gets two different answers. A phantom runs the same query twice and gets new rows. The lost update in this transfer (read the balance, compute in Java, write it back) can still happen at READ_COMMITTED. There are three fixes: an atomic UPDATE ... SET amount = amount - ?, a locking SELECT ... FOR UPDATE, or optimistic locking with a @Version column.

What the proxy actually does. Before the method runs, the transaction manager borrows a connection, turns off auto-commit and binds the connection to the current thread. Every JdbcTemplate or repository call on that thread reuses the same connection, which is how separate statements end up in one transaction. When the method returns, it commits. When it throws a runtime exception, it rolls back. Then it releases the connection. Because the binding is per thread, work you hand to another thread (@Async, a parallel stream) is not in the transaction.

PropagationIf a transaction already existsIf none exists
REQUIRED (default)Join itStart one
REQUIRES_NEWPause it and start a separate oneStart one
NESTEDSavepoint inside it; can roll back aloneStart one
SUPPORTSJoin itRun without one
MANDATORYJoin itThrow
NOT_SUPPORTEDPause it, run without oneRun without one
NEVERThrowRun without one

The rules you need to know

Rollback rules
  • Unchecked exceptions (RuntimeException, Error) roll back.
  • Checked exceptions (IOException, your own extends Exception) commit by default. Use @Transactional(rollbackFor = Exception.class) if you need them to roll back.
  • An exception you catch inside the method never reaches the proxy, so the half-finished work gets committed and the logs say everything is fine. Everything is not fine.
what not to do
@Transactional
public void transfer(...) {
    try {
        debit(...);
        credit(...);              // throws
    } catch (RuntimeException e) {
        log.warn("transfer failed", e);   // swallowed, so Spring COMMITS the debit alone
    }
}

// Self-invocation: the inner call skips the proxy, so there's no transaction at all
public void transferMany(List<TransferRequest> requests) {
    requests.forEach(r -> this.transferMoney(...));   // "this" is not the proxy
}
What a rollback can't undo
  • Only the database rolls back. An email sent, an HTTP call made or a message published inside the method stays done. Do those after the commit, for example in a @TransactionalEventListener (it runs after commit by default).
  • A rollback is not a retry. Spring undoes the changes and rethrows the exception. Running the work again is your decision (Spring Retry, or a loop in the caller).
  • A caught inner failure can still sink the whole transaction. If an inner @Transactional method joins the outer transaction (REQUIRED) and throws, it marks the whole transaction rollback-only. Catching the exception in the outer method doesn't help: the commit fails with UnexpectedRollbackException. Use REQUIRES_NEW if the inner work really is independent.
  • Chapter 6's proxy rules apply. @Transactional on a private method, a self-invoked method or an object made with new does nothing. Work handed to another thread (@Async) runs outside the transaction.
AttributeCommon valuesUse
propagationREQUIRED (default): join the caller's transaction or start one. REQUIRES_NEW: always a separate transaction.REQUIRES_NEW for an audit log that must be saved even if the main work rolls back
readOnlytrueQuery-only service methods; lets the driver optimise
isolationREAD_COMMITTED (Postgres default), REPEATABLE_READ, SERIALIZABLEStricter levels prevent concurrency anomalies, at a cost
timeoutsecondsStop runaway transactions
Bugs in TransferService that @Transactional won't save you from
  1. Lost update. The service reads the balance, does the maths in Java, then writes the result. If two transfers from Cage run at the same time, both read 1000, and the second write overwrites the first. One debit vanishes.
  2. Negative amounts. amount = -100 passes the balance check and moves money from Rita to Cage.
  3. Sender equals receiver. Transfer 100 from Cage to Cage: both reads return 1000, the service writes 900, then writes 1100. Cage gains 100.

Fix 2 and 3 with validation (Part 5A). Fix 1 by letting the database do the arithmetic atomically:

repositories/AccountRepository.java
// The check and the change happen in ONE statement, so concurrent transfers can't interleave.
// Returns the number of rows changed: 0 means not enough money (or no such account).
@Modifying
@Query("UPDATE account SET amount = amount - :amount WHERE id = :id AND amount >= :amount")
int debit(@Param("id") long id, @Param("amount") BigDecimal amount);

@Modifying
@Query("UPDATE account SET amount = amount + :amount WHERE id = :id")
int credit(@Param("id") long id, @Param("amount") BigDecimal amount);

// TransferService
@Transactional
public void transferMoney(long senderId, long receiverId, BigDecimal amount) {
    if (accountRepository.debit(senderId, amount) == 0) {
        throw new NotEnoughMoneyException(amount.doubleValue(), 0);
    }
    if (accountRepository.credit(receiverId, amount) == 0) {
        throw new IllegalArgumentException("Account not found: " + receiverId);   // rolls back the debit
    }
}

To watch transactions begin and end in the log, set logging.level.org.springframework.transaction.interceptor=TRACE.

14
Harry Potter

Spring Data JDBC

You tell the Room of Requirement what you need and it appears, already equipped. With Spring Data, you write a repository as an interface with no implementation, and Spring Data builds the class at startup, the same trick as the HTTP interface in chapter 11. You get save, find and delete methods for free, and you only write SQL for the queries that need it. It took the least code in the whole repo, and it's some of the best code in it.

Comic-style portrait of The Room of Requirement
The Room of RequirementA repository: declare what you need and Spring builds it.

Dependency: swap the JDBC starter for Spring Data JDBC

spring-boot-starter-data-jdbc already includes spring-boot-starter-jdbc, so JdbcTemplate keeps working. The book replaces the old starter with the new one. Listing both is harmless but redundant. Keep the database driver from chapter 12.

pom.xml · inside <dependencies>
<!-- replaces spring-boot-starter-jdbc (it includes it) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
model/HiddenItem.java + repositories/HiddenItemRepository.java
public record HiddenItem(@Id Long id, String name, String hiddenBy, int year) { }
// id null → save() INSERTs and returns a copy with the generated id
// id set  → save() UPDATEs

public interface HiddenItemRepository extends CrudRepository<HiddenItem, Long> {

    @Query("SELECT * FROM hidden_item WHERE hidden_by = :wizard")
    List<HiddenItem> findItemsHiddenBy(@Param("wizard") String wizard);

    @Modifying
    @Query("UPDATE hidden_item SET hidden_by = :wizard WHERE id = :id")
    void changeOwner(@Param("id") long id, @Param("wizard") String wizard);
}

Notice findById returns an Optional, because the item might not exist and Spring Data refuses to pretend otherwise. Call orElseThrow() when it must exist.

Spring Data, the bigger picture

Spring Data is a family, not one library. Spring Data JDBC, JPA, MongoDB, Redis, R2DBC and Elasticsearch all share the same repository model: declare an interface and the module implements it for its own store.

InterfaceGives you
Repository<T, ID>Nothing. It's a marker. You declare only the methods you want.
CrudRepository / ListCrudRepositorysave, findById, findAll, count, delete. The List version returns List instead of Iterable.
PagingAndSortingRepositoryfindAll(Sort) and findAll(Pageable). It doesn't include CRUD, so you extend both.

How it works. At startup, Spring finds every repository interface and creates a proxy for it. Built-in methods go to a ready-made implementation. Methods with @Query run your SQL as written. Every other method name gets parsed into a query: findByNameAndAmountGreaterThan becomes WHERE name = ? AND amount > ?. A typo in a derived method name fails at startup, not at 3 a.m., which is the kindest thing a framework has ever done for you.

AspectSpring Data JDBC (this repo)Spring Data JPA (Hibernate)
ModelPlain objects, one aggregate per repositoryManaged entities in a persistence context
When SQL runsImmediately, when you call saveLater, at flush or commit. Changed entities are saved automatically ("dirty checking")
RelationshipsSimple; no lazy loadingLazy loading, cascades, caching
SurprisesFewN+1 queries, LazyInitializationException, an UPDATE you never wrote

Start with JDBC when you want to see every query. Pick JPA when you have a rich domain model and are willing to learn its rules. Chapter 14 of the book stops at JDBC on purpose.

Derived queries, List return types, pagingYou don't need @Query for simple lookups. Spring Data reads the method name and writes the SQL. Yes, really. Name a method well and it just works, which is more than most method names can say.
repositories/HiddenItemRepository.java
// ListCrudRepository returns List instead of Iterable; the paging interface adds Pageable/Sort
public interface HiddenItemRepository
        extends ListCrudRepository<HiddenItem, Long>, ListPagingAndSortingRepository<HiddenItem, Long> {

    List<HiddenItem> findByName(String name);                        // WHERE name = ?
    List<HiddenItem> findByYearGreaterThan(int year);                 // WHERE year > ?
    List<HiddenItem> findByNameContainingIgnoreCase(String part);     // WHERE UPPER(name) LIKE UPPER(?)
    boolean existsByName(String name);
    long countByHiddenBy(String wizard);
}

// Paging in the controller:  GET /items?page=0&size=20
Page<HiddenItem> page = hiddenItemRepository.findAll(PageRequest.of(0, 20, Sort.by("name")));

A GET /items that returns every row is fine with four items and a disaster with four million. Always page.

AspectSpring Data JDBC (yours)Spring Data JPA (Hibernate)
ModelSimple: load, save, doneManaged entities, dirty checking, lazy loading
SQLPredictable; you see what runsGenerated; can surprise you (N+1 queries)
RelationshipsAggregates only@OneToMany, @ManyToMany…
Use whenYou want control and simplicityA rich domain model with many relations

Mapping is by naming convention. When a table or column name differs, use @Table("hidden_items") and @Column("hidden_by_wizard").

Part 4 · chapter 15

Testing

Many fast unit tests, fewer slice tests, a handful of full integration tests.

15
The Truman Show

Unit, slice and integration tests

Truman lives in a world built to see how he behaves. Tests build the same kind of world for your classes: fake neighbours (mocks) for fast unit tests, a partly real world for slice tests, and the real thing, with a real database, for integration tests. Tests check that your code does what you expect. There are three kinds: fast unit tests that test one class with fake dependencies (mocks), slice tests that start one layer of Spring, and integration tests that start the whole app with a real database. This chapter covers all three.

Comic-style portrait of Truman Burbank
Truman BurbankThe real class under test, in a world of mocks.
Comic-style portrait of Christof
Christofverify(): watches every call from the control room.
What to test, and with what

The test pyramid. Write many fast unit tests (one class, no Spring, milliseconds each), fewer slice tests (one layer with real Spring wiring, such as @WebMvcTest), and a handful of slow integration tests (the whole app, a real database). Turn it upside down and every build takes 20 minutes, so people stop running the tests.

Shape every test the same way. Arrange the inputs and fakes, Act once, Assert the result. (Also called given / when / then.) Test behaviour, not implementation. If renaming a private method breaks a test, the test was spying on you.

Test doubleWhat it doesMockito
StubReturns canned answerswhen(repo.findById(1L)).thenReturn(Optional.of(acc))
MockA stub that also records calls, so you can check themverify(repo).changeAmount(1L, ...)
SpyA real object with some methods overriddenMockito.spy(realService)
FakeA working, simpler implementationAn in-memory repository; Testcontainers is the opposite approach
DummyPassed in but never usedmock(Clock.class) just to satisfy a constructor
the unhappy path deserves a test too
@Test
void transferMoney_senderMissing_throws() {
    when(accountRepository.findById(1L)).thenReturn(Optional.empty());

    assertThrows(IllegalArgumentException.class,         // what orElseThrow throws in TransferService
        () -> transferService.transferMoney(1L, 2L, new BigDecimal("100.00"), false));

    verify(accountRepository, never()).changeAmount(anyLong(), any());   // no money moved
}

@InjectMocks can build the class under test from the @Mock fields, but calling the constructor yourself (as the test below does) fails at compile time instead of quietly injecting null. The rest of the toolbox: @BeforeEach for fresh setup per test, @ParameterizedTest for running one test over many inputs, and a coverage tool (JaCoCo) to find code no test has ever visited.

Dependency: the test starter

Every project from start.spring.io already has spring-boot-starter-test, in test scope so it never ends up in your production jar. It bundles JUnit 5 (Jupiter), Mockito, AssertJ, Hamcrest, JSONPath and Spring's own test support. Web slice tests (@WebMvcTest) also need spring-boot-starter-webmvc-test.

pom.xml · inside <dependencies>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<!-- run with:  ./mvnw test -->

Unit test: no Spring, mocked dependencies

TransferServiceTest.java
@ExtendWith(MockitoExtension.class)
class TransferServiceTest {
    @Mock private AccountRepository accountRepository;
    private TransferService transferService;

    @BeforeEach
    void setUp() { transferService = new TransferService(accountRepository); }

    @Test
    void transferMoney_enoughMoney_updatesBothAccounts() {
        // Arrange
        when(accountRepository.findById(1L)).thenReturn(Optional.of(new Account(1L, "William Cage", new BigDecimal("1000.00"))));
        when(accountRepository.findById(2L)).thenReturn(Optional.of(new Account(2L, "Rita Vrataski", new BigDecimal("1000.00"))));
        // Act
        transferService.transferMoney(1L, 2L, new BigDecimal("100.00"), false);
        // Assert
        verify(accountRepository).changeAmount(1L, new BigDecimal("900.00"));
        verify(accountRepository).changeAmount(2L, new BigDecimal("1100.00"));
    }
}

Constructor injection is what makes this easy: new TransferService(mock). With field injection you couldn't set the dependency without Spring.

Integration test: real Spring, real database

TransferServiceIntegrationTest.java
@SpringBootTest
@ActiveProfiles("test")      // loads application-test.properties → the_beef_test DB
class TransferServiceIntegrationTest {
    @Autowired private TransferService transferService;
    @Autowired private AccountRepository accountRepository;

    private long cageId;
    private long ritaId;

    // Nothing rolls back for us (see below), so every test starts from the same known rows,
    // whatever the previous test committed.
    @BeforeEach
    void freshAccounts() {
        accountRepository.deleteAll();
        cageId = accountRepository.save(new Account(null, "William Cage", new BigDecimal("1000.00"))).id();
        ritaId = accountRepository.save(new Account(null, "Rita Vrataski", new BigDecimal("1000.00"))).id();
    }

    @Test
    void transfer_failureInsideTransaction_rollsBack() {
        assertThatThrownBy(() -> transferService.transferMoney(cageId, ritaId, new BigDecimal("100.00"), true))
            .isInstanceOf(IllegalStateException.class);
        assertThat(balanceOf(cageId)).isEqualByComparingTo("1000.00");   // the debit was undone
    }

    private BigDecimal balanceOf(long id) {
        return accountRepository.findById(id).orElseThrow().amount();
    }
}
Why the test class has no @TransactionalThe test class deliberately has no @Transactional. Spring would have rolled back each test's own transaction and hidden the commit/rollback behaviour you're testing. The cost is that nothing cleans up for you: committed rows stay in the database. That's why @BeforeEach deletes the accounts and creates them again, so no test depends on what an earlier one left behind. Also note isEqualByComparingTo: BigDecimal.equals treats 900.0 and 900.00 as different.
Web slice test with MockMvcRight now nothing checks that /transfer actually returns 400. A web slice test checks one controller over HTTP, including JSON conversion, status codes and your @RestControllerAdvice, without starting a server or a database. It needs spring-boot-starter-webmvc-test (test scope), and @MockitoBean puts a mock into its context.
controllers/TransferControllerTest.java
@WebMvcTest(TransferController.class)     // only the web layer for this controller
class TransferControllerTest {

    @Autowired private MockMvc mockMvc;

    @MockitoBean private TransferService transferService;       // a mock placed in the context
    @MockitoBean private AccountRepository accountRepository;

    @Test
    void transfer_notEnoughMoney_returns400() throws Exception {
        doThrow(new NotEnoughMoneyException(500, 100))
            .when(transferService).transferMoney(1L, 2L, new BigDecimal("500"), false);

        mockMvc.perform(post("/transfer")
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {"senderId": 1, "receiverId": 2, "amount": 500}
                    """))
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.message").value(containsString("Not enough money")));
    }

    @Test
    void accounts_returnsJsonArray() throws Exception {
        when(accountRepository.findAll()).thenReturn(List.of(new Account(1L, "William Cage", BigDecimal.TEN)));

        mockMvc.perform(get("/accounts"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$[0].name").value("William Cage"));
    }
}
A throwaway database with TestcontainersAn integration test that needs a local Postgres with a the_beef_test database only passes on machines that have one, and never on a CI server. Testcontainers starts a real Postgres in Docker for the test run. Because DataSourceConfig reads spring.datasource.* with @Value, pass the container's details through @DynamicPropertySource. @ServiceConnection only feeds Boot's own auto-configured DataSource.
TransferServiceIntegrationTest.java
// pom (test scope): spring-boot-testcontainers, testcontainers-junit-jupiter, testcontainers-postgresql
@SpringBootTest
@Testcontainers
class TransferServiceIntegrationTest {

    @Container
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");

    @DynamicPropertySource
    static void datasource(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }
    // ...plus the same fields, @BeforeEach freshAccounts() and tests as above.
    // The container is new for each run, and @BeforeEach resets the rows between tests.
}
A data slice testThe table below lists @DataJdbcTest, but no test uses it yet. It loads only the repositories and a DataSource, and rolls back after each test, so tests can't leak data into each other. The slice comes from its own test starter (spring-boot-starter-data-jdbc-test); start.spring.io adds it for you. Replace.NONE means "use whatever spring.datasource.url points to". On its own, that could be your development database, so the test starts its own Postgres container the same way the integration test above does.
repositories/HiddenItemRepositoryTest.java
@DataJdbcTest                                         // repositories + DataSource only
@AutoConfigureTestDatabase(replace = Replace.NONE)    // keep spring.datasource.*, don't swap in an embedded DB
@Testcontainers
class HiddenItemRepositoryTest {

    @Container
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");

    @DynamicPropertySource                            // ...and point spring.datasource.* at the container
    static void datasource(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Autowired private HiddenItemRepository hiddenItemRepository;

    @Test
    void findItemsHiddenBy_returnsOnlyThatWizardsItems() {
        hiddenItemRepository.save(new HiddenItem(null, "Advanced Potion-Making", "Harry", 1996));
        hiddenItemRepository.save(new HiddenItem(null, "Vanishing Cabinet", "Draco", 1996));

        assertThat(hiddenItemRepository.findItemsHiddenBy("Harry"))
            .extracting(HiddenItem::name)
            .containsExactly("Advanced Potion-Making");
    }
}
Test typeAnnotationStartsSpeedProves
Unit@ExtendWith(MockitoExtension.class)NothingmsBusiness logic
Web slice@WebMvcTestMVC layer only~1 sURLs, JSON, status codes, error handlers
Data slice@DataJdbcTestRepositories + DBsecondsYour SQL and @Query methods
Integration@SpringBootTestEverythingsecondsWiring, transactions, real flows

To measure coverage, add the jacoco-maven-plugin and run ./mvnw verify. The report is written to target/site/jacoco/index.html. Open it, then try not to look directly at the number.

Part 5 · beyond the book

Making it production ready

Everything that stands between the code in this guide and production, applied to that code.

A
Ocean's Eleven

Validating input

Every chip is checked at the cage before anything is paid out. Validation does the same at your controller's door. Validation checks incoming data before your code uses it. Right now POST /transfer accepts negative amounts and lets an account send money to itself (see chapter 13). With validation, bad input is rejected at the controller, before the service ever sees it.

model/TransferRequest.java + controller
public record TransferRequest(
        @Positive long senderId,
        @Positive long receiverId,
        @NotNull @DecimalMin("0.01") @Digits(integer = 8, fraction = 2) BigDecimal amount) {

    // A rule that spans two fields
    @AssertTrue(message = "sender and receiver must be different accounts")
    public boolean isDifferentAccounts() {
        return senderId != receiverId;
    }
}

@PostMapping("/transfer")
public void transfer(@Valid @RequestBody TransferRequest request, ...) { ... }   // @Valid triggers it

// In ExceptionControllerAdvice: turn failures into a readable 400
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail invalid(MethodArgumentNotValidException e) {
    ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
    problem.setTitle("Invalid request");
    problem.setProperty("errors", e.getBindingResult().getAllErrors().stream()
        .map(DefaultMessageSourceResolvable::getDefaultMessage)
        .toList());
    return problem;
}

Other useful constraints: @NotBlank, @Size(max = 50) (to match VARCHAR(50)), @Email and @Pattern. Keep the database constraints (NOT NULL, UNIQUE) as well. Validation stops bad requests, and constraints protect the data.

B
Ocean's Eleven

Spring Security

Benedict's vault doesn't let anyone in just because they walked up to it. Spring Security controls who can use your app. The chapter 9 login (password "password", a session bean, logout over GET) shows the idea, but in production Spring Security replaces all of it. Today anyone who can reach the server can call POST /transfer without logging in. Once the starter is on the classpath, every endpoint requires login by default.

Authentication, authorization and the filter chain

Authentication asks "who are you?" and answers 401 Unauthorized when it can't tell. Authorization asks "are you allowed?" and answers 403 Forbidden when you aren't. Yes, the 401 name is wrong. No, nobody will fix it.

Request→Security filter chain→DispatcherServlet→Controller

Spring Security is a chain of servlet filters that runs before DispatcherServlet, so a rejected request never reaches your controller. One filter reads the credentials (a form login, a session cookie, a bearer token). Another checks them against a UserDetailsService. The result is an Authentication object stored in the SecurityContext, which is bound to the thread just like transactions are. Later filters, and @PreAuthorize on methods, use it to decide access.

Passwords are hashed, never stored. BCrypt is one-way, adds a random salt to each password and is deliberately slow, so a stolen table takes years to crack instead of minutes. Sessions or tokens: server-rendered apps usually keep a session cookie, which needs CSRF protection. Stateless APIs usually take a bearer token (often a JWT) in the Authorization header.

config/SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 1. The JSON API (POST /transfer, GET /accounts): bearer tokens, no session, no cookies
    @Bean
    @Order(1)
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/transfer", "/accounts/**")
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/transfer").hasAuthority("SCOPE_transfer")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable());   // safe only because this chain uses no cookies
        return http.build();
    }

    // 2. The server-rendered pages: form login and a session cookie
    @Bean
    @Order(2)
    SecurityFilterChain pages(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/login", "/css/**").permitAll()
                .anyRequest().authenticated())
            .formLogin(form -> form.loginPage("/login").defaultSuccessUrl("/main"))
            .logout(Customizer.withDefaults());   // POST /logout
        // CSRF protection stays on (the default). Thymeleaf adds the token to every POST form.
        return http.build();
    }

    // Hashes passwords (bcrypt by default). Never store or compare plain text.
    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    // Users come from the database (tables: users, authorities)
    @Bean
    UserDetailsManager users(DataSource dataSource) {
        return new JdbcUserDetailsManager(dataSource);
    }
}

// Anywhere in a controller: who is logged in?
@GetMapping("/main")
public String main(@AuthenticationPrincipal UserDetails user, Model model) {
    model.addAttribute("username", user.getUsername());
    return "main.html";
}
ConceptReplaces in this guide's code
SecurityFilterChainThe if (username == null) return "redirect:/" checks in TableController
UserDetailsService + PasswordEncoderTicketProcessor and the hard-coded password
SecurityContext (from the session for pages, from the token for the API)TableTab
CSRF protectionNothing: today the POST forms accept cross-site requests. The page chain keeps Spring Security's CSRF protection on. The API chain turns it off because a bearer token isn't sent automatically the way a cookie is.

The two chains follow the rule above. Pages use a session cookie, so they need CSRF protection. /transfer is a JSON API, so it takes a bearer token instead. The API chain needs spring-boot-starter-oauth2-resource-server and the token issuer's address in spring.security.oauth2.resourceserver.jwt.issuer-uri. Spring then checks each token's signature and expiry and turns its scopes into SCOPE_… authorities. Method-level rules use @EnableMethodSecurity with @PreAuthorize("hasRole('ADMIN')"), which is another proxy-based aspect.

C
Ocean's Eleven

Profiles and secrets

The crew rehearses in a replica vault, then does the same moves in the real one. Profiles give your app that split: the same code, with different settings for each environment. Profiles let the same code run with different settings in each environment: your laptop, the tests and production. The tests already use a profile (test), and the password stays out of git in application-local.properties. Extend the same pattern:

Where a property value actually comes from

Spring Boot reads properties from many sources, and the more specific one wins. From highest to lowest:

  1. Command-line arguments: --server.port=9090
  2. Environment variables: SERVER_PORT=9090. Dots become underscores and the name is upper-cased (this is called relaxed binding).
  3. Profile files: application-prod.properties
  4. application.properties / application.yml
  5. Defaults in code

That's why the same jar can run in every environment: package it once and change only the environment. Read single values with @Value("${app.name}"), or a whole group with a @ConfigurationProperties record, which is type-safe and can be validated.

src/main/resources/
# application.properties         shared defaults, no secrets
# application-dev.properties     local Postgres, verbose logging
# application-prod.properties    pool sizes, logging levels, no debug endpoints

# Choose at startup:
#   java -jar app.jar --spring.profiles.active=prod
#   or the environment variable  SPRING_PROFILES_ACTIVE=prod

# In production, secrets come from environment variables (or a vault), never from files in git.
# Relaxed binding: SPRING_DATASOURCE_PASSWORD sets spring.datasource.password
spring.datasource.password=${DB_PASSWORD}
a bean that exists only in one profile
@Configuration
@Profile("dev")
public class DevDataConfig {
    @Bean
    CommandLineRunner seedAccounts(AccountRepository repo) {
        return args -> repo.save(new Account(null, "Dev User", new BigDecimal("500.00")));
    }
}

Make sure application-local.properties is in .gitignore. If a password was ever committed, deleting the file isn't enough: it lives in git history forever. Change the password.

D
Ocean's Eleven

Database migrations

Every change to the building plans gets a new, numbered sheet. Database changes need the same discipline. Your database tables change as the app grows, and every change has to be applied once, in order, on every database. schema.sql with CREATE TABLE IF NOT EXISTS works only until you need to change a table: add a column to account and the script skips the table because it already exists. Flyway applies numbered scripts exactly once each, in order, and records which have run.

pom.xml + db/migration
# pom.xml: spring-boot-starter-flyway  +  org.flywaydb:flyway-database-postgresql
# then delete schema.sql and the spring.sql.init.mode line

src/main/resources/db/migration/
    V1__create_ticket.sql        -- the ticket table from schema.sql
    V2__create_account.sql       -- the account table + the two seed rows
    V3__add_account_currency.sql -- ALTER TABLE account ADD COLUMN currency CHAR(3) NOT NULL DEFAULT 'EUR';
Golden ruleNever edit a migration that has already run anywhere. Flyway checksums each file and refuses to start if one changes. Flyway remembers. Flyway always remembers. To fix a mistake, add a new V4__... script.
E
Ocean's Eleven

Logging

Livingston watches every camera feed but only speaks up when something matters. Good logging works the same way. Logs record what your app is doing, so you can find out what went wrong after the fact. Good logs are quiet until something matters. Spring Boot logs through SLF4J, with Logback underneath, and the chapter 6 aspects already use it. Give each class its own logger:

PaymentController.java
private static final Logger log = LoggerFactory.getLogger(PaymentController.class);  // org.slf4j

log.info("Received payment {}", payment.amount());   // the message is built only if INFO is on
log.debug("Full payment {}", payment);                // hidden unless DEBUG is on
log.error("Payment failed for {}", requestId, ex);    // the exception goes LAST, with its stack trace
application.properties
logging.level.root=INFO
logging.level.com.example.thebeef=DEBUG
logging.level.org.springframework.jdbc.core=DEBUG       # print every SQL statement JdbcTemplate runs
logging.level.com.zaxxer.hikari=DEBUG                   # watch the connection pool

Placeholders skip the string formatting when a level is off. They don't skip the arguments: payment.amount() above runs either way. That's fine for cheap values. For an expensive one, check the level first with if (log.isDebugEnabled()), or pass a supplier that runs only when the level is on: log.atDebug().setMessage("Report {}").addArgument(() -> buildReport()).log().

Never log passwords, tokens or full card numbers. Mask anything sensitive before it reaches a log line, and never hard-code passwords the way the chapter 9 login does.

F
Ocean's Eleven

Health and metrics with Actuator

Benedict's security room shows at a glance whether every door, camera and lock is working. In production you need to know whether your app is running and healthy. Actuator adds endpoints that report whether the app is up and how busy it is.

application.properties
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.probes.enabled=true      # /actuator/health/liveness and /readiness for Kubernetes
management.endpoint.health.show-details=when-authorized
EndpointShows
/actuator/healthUP/DOWN, including a database check through your DataSource
/actuator/metrics/hikaricp.connections.activeHow busy your pool is
/actuator/metrics/http.server.requestsRequest counts and latency per endpoint

Expose as little as you need. env, heapdump and configprops can reveal secrets. Keep them off, or behind Spring Security.

G
Ocean's Eleven

Build and run

Everything the crew needs goes into one van. To run your app on a server, you package it. The Spring Boot build makes one executable jar with your code, every dependency and Tomcat inside, which runs anywhere Java 17 is installed.

terminal
# run the app from source
./mvnw spring-boot:run

# run tests, build one executable jar (Tomcat inside)
./mvnw clean verify
java -jar target/the-beef-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

# build a container image with no Dockerfile (needs Docker running)
./mvnw spring-boot:build-image

# graceful shutdown: finish in-flight requests before stopping
server.shutdown=graceful

On Windows, use mvnw.cmd / gradlew.bat, or just .\mvnw in PowerShell. Gradle also builds a second, plain jar ending in -plain.jar; that's the one without dependencies, so run the other one.

Part 6 · everything together

A real app: one to-go order at The Original Beef

One tap in a food-delivery app passes through almost every chapter of this guide, and every single one of them can ruin Sam's dinner. Choose what goes wrong, press Order, and watch each Spring feature do its job. The yellow tag tells you which chapter explains each step.

★
The Bear · every chapter together

The Original Beef: one order, end to end

Try it · Sam orders 2 Italian beefs

The shop starts with 5 sandwiches. Keep ordering until it sells out.
readyChoose what should happen, then press Order.
Phone appSam's order
Security filterwho is calling?
OrderController@Valid request
OrderService@Transactional
PaymentsClientHTTP interface · 3 s timeout
CyranoAspect@Whispered
PostgreSQLcommitted data
Italian beefs in stock5
Orders saved0
Payment providerexternal API
No order yet
What to notice
  • Each failure is stopped at the earliest layer that can catch it: security, then validation, then business rules.
  • After the transaction opens, any failure rolls back everything. The stock and order count end up exactly as they were.
  • The "too slow" case only ends because the client has a timeout (chapter 11). Without one, the open transaction and the request thread would wait forever.
★★
Your turn

Final challenge: build the order service

The simulator above shows a finished order flow. Now build it yourself as a small Spring Boot app, using only what this guide covers. Work through the steps in order. A step is done when its check passes, not when the code compiles.

What you're building
  • GET /menu lists the items, with price and stock.
  • POST /orders with {"itemId": 1, "quantity": 2} places an order. It reserves stock, charges the payment, and saves the order, all in one transaction.
  • GET /orders/{id} returns one order, or 404.
StepBuildUsesDone when
1A project from start.spring.io with Web, Data JDBC, PostgreSQL, Validation, Flyway and Testcontainers.ch 7, D./mvnw verify passes on the empty app.
2Flyway V1 creates menu_item (id, name, price NUMERIC(8,2), stock INT CHECK (stock >= 0)) and orders (id, item_id, quantity, total, created_at). V2 seeds three items.ch 12, DThe app starts against a Testcontainers Postgres, and both tables exist.
3MenuItemRepository and OrderRepository as Spring Data interfaces, plus one @Modifying @Query method, reserveStock(id, qty), that runs UPDATE menu_item SET stock = stock - :qty WHERE id = :id AND stock >= :qty and returns the row count. Map the order record with @Table("orders"), because order is a reserved word in SQL.ch 13, 14A @DataJdbcTest shows reserveStock returns 0 when there isn't enough stock.
4OrderService gets both repositories and a PaymentsClient interface through its constructor. The first PaymentsClient is a fake @Component that declines any amount over 100.00.ch 3, 4A Mockito unit test, with no Spring, covers success, sold out and declined.
5placeOrder is @Transactional: reserve the stock, charge the payment, save the order. Throw unchecked SoldOutException and PaymentDeclinedException.ch 13An integration test shows a declined payment leaves the stock unchanged and saves no order.
6OrderController takes @Valid OrderRequest(@Positive long itemId, @Min(1) @Max(10) int quantity) and returns 201 with a Location header. A @RestControllerAdvice maps validation to 400, sold out to 409 and declined to 402, as ProblemDetail.ch 10, AA @WebMvcTest checks every status code.
7Stretch goals: protect POST /orders with a bearer-token chain, replace the fake payment client with an HTTP interface that has a 3-second timeout, and expose /actuator/health.ch 11, B, FAn unauthenticated POST /orders gets 401, and a stuck payment provider fails the order after 3 seconds with the stock unchanged.
House rules
  • Constructor injection only. If you write new for a class that should be a bean, stop and ask why.
  • Every test creates the data it needs. No test depends on another one running first.
  • Every failure in the simulator's "What happens" list should end up with a test that proves it.
Reference · which story teaches what

Story map

Each story was chosen because its plot already works like the idea. Real scenes come first; where the plot runs out, new scenes continue in the same world.

ChStoryScenesTeaches
1–3Ocean's ElevenDanny recruits a crew instead of doing it all; Rusty's notebook; Linus shadows FrankContext, beans, @Bean vs @Component, injection styles, circular dependencies
4The Princess BrideThe title Dread Pirate Roberts passes from man to manInterfaces, @Primary, @Qualifier, the two startup errors
5The PrestigeAngier's machine makes a new copy each night; Borden is twinsPrototype vs singleton, ObjectProvider, @Lazy, thread safety
6Cyrano de BergeracCyrano feeds Christian his lines under the balconyProxies, advice, proceed(), @Order, self-invocation
7–9The BearThe brigade system; the to-go pre-order meltdown in “Review”; the all-day countTomcat, DispatcherServlet, views vs JSON, thread pools, web scopes
10–11MementoLeonard's notes, Polaroids and phone callsStatelessness, trust, status codes, REST clients, timeouts
12The BearThe kitchen's pansConnection pool, leaks, JdbcTemplate, SQL injection
13Edge of TomorrowCage relives the day each time he dies; Rita's reset; the transfusionCommit, rollback, rollback rules, side effects, lost updates
14Harry PotterThe Room of RequirementRepositories, derived queries, @Query, paging
15The Truman ShowTruman's town of actors and the painted skyMocks, verify, unstubbed defaults, slice and integration tests
A–GOcean's ElevenThe night of the job: the cage, the vault, the replica, the blueprintsValidation, security, profiles, migrations, logging, Actuator, build
Reference

Annotation cheat sheet

AnnotationWhat it doesCh
@ConfigurationClass holds @Bean methods (proxied so calls return the same bean)2
@BeanMethod's return value becomes a bean named after the method2
@Component / @Service / @RepositorySpring creates this class as a bean when scanning2, 4
@ComponentScanWhich packages to scan2
@PostConstruct / @PreDestroyRun after creation / before the context closes2, 5
@AutowiredInject a dependency (optional on a single constructor)3
@Qualifier("name")Pick one bean among several of the same type3, 4
@PrimaryDefault choice among several of the same type4
@LazyCreate on first use instead of at startup5
@Scope("prototype")New instance each time it's requested5
@Aspect + @EnableAspectJAutoProxyDefine aspects / turn them on (automatic in Boot)6
@Before @After @AfterReturning @AfterThrowing @AroundWhen advice runs relative to the method6
@Order(n)Aspect order: lower = outer6
@SpringBootApplicationConfiguration + component scan + auto-configuration7
@ConfigurationPropertiesBind a group of properties to a typed object7
@Value("${key}")Inject a single property11, 12
@Controller / @RestControllerWeb endpoints returning views / JSON7, 10
@GetMapping @PostMapping @RequestMappingMap URL + HTTP method to a method7, 8
@RequestParam @PathVariable @RequestHeader @RequestBodyRead query, path, header, JSON body8, 10
@ModelAttributeBind form fields to an object8
@RequestScope @SessionScope @ApplicationScopeWeb bean lifetimes9
@ResponseStatusFixed status code for a method or exception10, 12
@RestControllerAdvice + @ExceptionHandlerTurn exceptions into HTTP responses for all controllers10
@FeignClient / @HttpExchangeDeclarative HTTP clients11
@TransactionalRun the method in one transaction; roll back on unchecked exceptions13
@Id @Table @ColumnSpring Data mapping14
@Query + @ModifyingCustom SQL on a repository method; @Modifying for writes14
@SpringBootTest @WebMvcTest @DataJdbcTestFull context / web slice / data slice15
@MockitoBean / @MockMock inside a Spring test / plain Mockito mock15
@ActiveProfiles / @ProfileChoose profile in a test / bean exists only in a profile15, C
@Valid + constraintsValidate a request bodyA
@EnableWebSecurity @PreAuthorizeSecurity config / method-level access rulesB
Reference · what to add, chapter by chapter

Dependency cheat sheet

Boot rows have no version because the parent (Maven) or the Boot plugin (Gradle) supplies it. Gradle lines go inside dependencies { }.

ChFeatureMaven groupId : artifactIdGradle
2Spring context (plain Spring)org.springframework : spring-context : 7.0.8implementation "org.springframework:spring-context:7.0.8"
2@PostConstruct / @PreDestroy (plain Spring)jakarta.annotation : jakarta.annotation-api : 3.0.0implementation "jakarta.annotation:jakarta.annotation-api:3.0.0"
6Aspects (plain Spring)org.springframework : spring-aspects : same versionimplementation "org.springframework:spring-aspects:7.0.8"
6Aspects (Boot)org.springframework.boot : spring-boot-starter-aspectjimplementation "org.springframework.boot:spring-boot-starter-aspectj"
7Boot version management<parent> spring-boot-starter-parent 4.1.1plugins: org.springframework.boot 4.1.1 + io.spring.dependency-management
7–10Spring MVC, Tomcat, Jacksonorg.springframework.boot : spring-boot-starter-webmvcimplementation "org.springframework.boot:spring-boot-starter-webmvc"
8Thymeleaf viewsorg.springframework.boot : spring-boot-starter-thymeleafimplementation "org.springframework.boot:spring-boot-starter-thymeleaf"
11Spring Cloud BOMorg.springframework.cloud : spring-cloud-dependencies : 2025.1.3 (import)dependencyManagement { imports { mavenBom "…:spring-cloud-dependencies:2025.1.3" } }
11OpenFeignorg.springframework.cloud : spring-cloud-starter-openfeignimplementation "org.springframework.cloud:spring-cloud-starter-openfeign"
11WebClientorg.springframework.boot : spring-boot-starter-webclientimplementation "org.springframework.boot:spring-boot-starter-webclient"
12–13JdbcTemplate + HikariCPorg.springframework.boot : spring-boot-starter-jdbcimplementation "org.springframework.boot:spring-boot-starter-jdbc"
12Driver: PostgreSQL / H2 / MySQLorg.postgresql : postgresql · com.h2database : h2 · com.mysql : mysql-connector-j (runtime)runtimeOnly "org.postgresql:postgresql"
14Spring Data JDBCorg.springframework.boot : spring-boot-starter-data-jdbcimplementation "org.springframework.boot:spring-boot-starter-data-jdbc"
15JUnit 5, Mockito, AssertJorg.springframework.boot : spring-boot-starter-test (test)testImplementation "org.springframework.boot:spring-boot-starter-test"
15@WebMvcTestorg.springframework.boot : spring-boot-starter-webmvc-test (test)testImplementation "org.springframework.boot:spring-boot-starter-webmvc-test"
ABean Validationorg.springframework.boot : spring-boot-starter-validationimplementation "org.springframework.boot:spring-boot-starter-validation"
BSpring Securityorg.springframework.boot : spring-boot-starter-securityimplementation "org.springframework.boot:spring-boot-starter-security"
DFlyway + Postgres supportspring-boot-starter-flyway · org.flywaydb : flyway-database-postgresqlimplementation "org.springframework.boot:spring-boot-starter-flyway"
FActuatororg.springframework.boot : spring-boot-starter-actuatorimplementation "org.springframework.boot:spring-boot-starter-actuator"