JAVA-260 · Lesson 1 of 12 · 28 min

How Spring Boot works

▶ Video coming soon A video version of this lesson is on the way.

On Wednesday evening, January 12, 2028, Odile Branscombe joined Ingrid and Hamza in the back room with a problem she had been carrying since the autumn. Every Saturday the shop's phone rang all morning with people asking two questions: can you look at my bike next week, and do you have the part it needs? The counter staff answered between customers, wrote bookings on a paper sheet and walked to the parts room to check bins. Odile wanted a booking page on the shop's website by the summer, where people could see free repair times, request one and check whether a part was in stock. "The page itself is Leif's department," Ingrid said. "What it needs behind it is a web service: a program on a server that the page, the counter computer and anything else can ask questions over HTTP. That is what we build this term, and we build it with Spring Boot."

This course follows the term week by week. Ingrid's Wednesday sessions run from January 12 to March 29, with no session in reading week, and the plan ends with a capstone in April: a REST service for the booking page, built on the StockStore database from JAVA-250 and on the ports Hamza is designing in his Tuesday design course, JAVA-270. Each lesson shows the Spring code a real project uses and, next to it, small programs that use only the JDK, so that you can see the mechanism underneath and run it yourself.

What a web service is

A web service is a program that listens for HTTP requests and answers with data rather than pages for people to read. The booking page in a browser, the counter computer's program and a phone app can all call the same service, and each shows the answers in its own way. Most services today follow the REST style: the service exposes resources, such as parts, repair slots and bookings, each named by a URL, and clients act on them with the standard HTTP methods. GET reads a resource, POST creates one, PUT replaces one, PATCH changes part of one and DELETE removes one. The answer carries a status code that says how it went, such as 200 OK, 201 Created, 404 Not Found or 409 Conflict, and a body, usually JSON.

The four questions Odile wants the booking page to ask, written as HTTP requests.
RequestMeaning for the booking serviceTypical answer
GET /api/v1/parts/BELLIs the brass bell in stock?200 with a small JSON object
GET /api/v1/repair-slots?date=2028-05-06Which repair times are free that Saturday?200 with a JSON list
POST /api/v1/repair-bookingsBook a repair slot201 Created, or 409 if the slot just filled
GET /api/v1/repair-bookings/2041What is happening with booking 2041?200, or 404 if there is no such booking

HTTP itself is plain text over a network connection, and Java has had everything needed to speak it for years. The JDK's java.net.http.HttpClient sends requests, and the JDK also includes a small HTTP server, com.sun.net.httpserver.HttpServer, meant for tools and tests. The example starts that server inside the program, on a free port that the operating system chooses, sends it two requests and stops it again. It is a whole web service in one file, and it is worth running once before Spring hides these details.

Java Example · Main.java
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/api/v1/hello", exchange -> {
            byte[] body = "{\"shop\":\"Second Gear Cycles\",\"open\":true}".getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().add("Content-Type", "application/json");
            exchange.sendResponseHeaders(200, body.length);
            try (var out = exchange.getResponseBody()) { out.write(body); }
        });
        server.start();
        try {
            String base = "http://127.0.0.1:" + server.getAddress().getPort();
            HttpClient client = HttpClient.newHttpClient();
            for (String path : new String[] {"/api/v1/hello", "/api/v1/nothing-here"}) {
                HttpRequest request = HttpRequest.newBuilder(URI.create(base + path)).GET().build();
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                System.out.println("GET " + path + " -> " + response.statusCode());
                if (response.statusCode() == 200) System.out.println("  " + response.body());
            }
        } finally {
            server.stop(0);
        }
    }
}
Output
GET /api/v1/hello -> 200
  {"shop":"Second Gear Cycles","open":true}
GET /api/v1/nothing-here -> 404

What this code does

The server is bound to port 0, which asks the operating system for any free port, and the program reads back the port it was given, so it never clashes with another program. The handler for /api/v1/hello writes a status, a Content-Type header and a JSON body, and any other path gets the server's own 404 answer. The finally block stops the server, so the program ends cleanly instead of leaving it listening.

Everything a real service needs is missing from that program. It has no routing beyond whole path prefixes, no JSON library, no validation, no database, no security, no error pages in a standard format, no metrics and no tests. Each of those can be written by hand, and in this course you will write small versions of several to understand them. A production team does not want to write and maintain them, though, and that is why most Java web services are built on a framework.

Spring, Spring Boot and what each adds

The Spring Framework started in 2003 as a lighter alternative to the heavy enterprise Java of the time. Its core is an inversion of control container, also called the application context: instead of each object creating the objects it needs, the container creates them, connects them and manages their life cycle. On top of that core, Spring offers modules for web applications (Spring MVC), data access, transactions, messaging and more, and sister projects such as Spring Data and Spring Security. Spring is open source and is developed by a team at Broadcom, which acquired VMware, its previous owner, in 2023.

Spring on its own needs a lot of configuration: which web server to run, how to turn objects into JSON, which database to connect to and with what pool. Spring Boot, first released in 2014, removes most of that work with three ideas. Starters are dependencies that bring in a tested set of libraries for one job, such as building web services. Auto-configuration looks at what is on the class path and in your settings and configures sensible beans for you, backing off whenever you define your own. And the embedded server means the application is one executable JAR that contains its own web server, so it starts with java -jar instead of being deployed into a separately installed server.

The parts of the Spring ecosystem this course uses.
PieceWhat it gives the booking service
Spring Framework 7The container, Spring MVC for REST controllers, transactions, the RestClient for calling other services
Spring Boot 4Starters, auto-configuration, the embedded Tomcat server, externalized configuration, Actuator for health and metrics
Spring Data JPARepository interfaces that generate data access code over JPA and Hibernate
Spring Security 7Authentication, authorization, password encoding, CORS and CSRF protection
springdoc-openapiAn OpenAPI description and a Swagger UI page generated from the controllers

At the time of writing, in November 2026, the current release line is Spring Boot 4, which arrived in November 2025 together with Spring Framework 7 and Spring Security 7. Spring Boot 4.1 followed in June 2026, and a 4.2 release was scheduled for late 2026, with new minor versions roughly every six months. Boot 4 needs Java 17 or later and supports Java 25, moves to the Jakarta EE 11 APIs, and uses Jackson 3 for JSON by default. Free open-source support for each minor version lasts about a year, so a project plans to move up regularly: Spring Boot 3.5's free support ended in June 2026. When you start a project, check the current version on the Spring website rather than copying a version number from a book or from this course.

Inversion of control in a few lines

Before looking at Spring code, it helps to see the problem the container solves. A booking service needs a repository that stores bookings, a clock that tells it the time, a price list and a notifier. If each class creates its own helpers with new, the classes are tied to one choice of each and are hard to test. The alternative is to have something outside the classes create the objects and pass each one the helpers it needs. That outside something can be your own main method, which is how the next example works, and Spring's container does the same job automatically for hundreds of objects.

Java Example · Main.java
import java.time.*;
import java.util.*;

public class Main {
    interface BookingStore { void save(String booking); List<String> all(); }

    static class MemoryBookingStore implements BookingStore {
        private final List<String> rows = new ArrayList<>();
        public void save(String booking) { rows.add(booking); }
        public List<String> all() { return List.copyOf(rows); }
    }

    static class BookingService {
        private final BookingStore store;
        private final Clock clock;
        BookingService(BookingStore store, Clock clock) { this.store = store; this.clock = clock; }

        String book(String customer, String bike) {
            String booking = LocalDate.now(clock) + " " + customer + " " + bike;
            store.save(booking);
            return booking;
        }
    }

    public static void main(String[] args) {
        // The "container" is just this method: it creates each object once and wires them together.
        BookingStore store = new MemoryBookingStore();
        Clock clock = Clock.fixed(Instant.parse("2028-01-12T23:30:00Z"), ZoneId.of("America/Toronto"));
        BookingService service = new BookingService(store, clock);

        System.out.println(service.book("Ana Ruiz", "commuter with a flat"));
        System.out.println(service.book("Theo Park", "cargo bike brakes"));
        System.out.println("Stored: " + store.all().size());
    }
}
Output
2028-01-12 Ana Ruiz commuter with a flat
2028-01-12 Theo Park cargo bike brakes
Stored: 2

What this code does

BookingService never says new for its helpers; it receives a BookingStore and a Clock in its constructor and uses whatever it is given. The main method plays the container's part, choosing an in-memory store and a fixed clock, which is exactly what a test would choose. The fixed instant is 23:30 UTC, which is still January 12 in the shop's time zone, so both bookings carry the right local date.

In a Spring application you mark BookingService with an annotation such as @Service, and the container finds it, sees that its constructor needs a BookingStore and a Clock, finds beans of those types and calls the constructor. Lesson 2 builds a tiny container that does this with reflection, and looks at how Spring decides which bean to use when there is more than one.

A first Spring Boot application

A new Spring Boot project is usually created with Spring Initializr, the start.spring.io website or the same wizard built into IntelliJ IDEA and VS Code. You choose the build tool, the Java version, the group and artifact names, and the starters you need, and it produces a project with a build file, a main class and an empty test. Hamza chose Gradle, as in the multi-module secondgear build from JAVA-120, Java 25, and the web starter. The build file below is what such a project contains, trimmed to the lines that matter.

build.gradle.kts
plugins {
    java
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

group = "org.secondgear"
version = "0.1.0"

java {
    toolchain { languageVersion = JavaLanguageVersion.of(25) }
}

repositories { mavenCentral() }

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-webmvc")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

What this code does

The Spring Boot Gradle plugin adds the bootRun and bootJar tasks and makes bootJar produce one executable JAR that contains every dependency. The dependency-management plugin lets the build leave version numbers off Spring dependencies, because each Boot release fixes a tested version of each library. The plugin version shown was current when this course was written; use the latest 4.x release when you start.

Spring Boot 4 split its starters and auto-configuration into smaller modules, one per technology, so the web starter for servlet-based services is now spring-boot-starter-webmvc. The older name spring-boot-starter-web still exists for compatibility in the 4.x releases, and you will see it in many articles written before Boot 4. Either way, the starter brings in Spring MVC, an embedded Tomcat server and Jackson for JSON.

Java Example · BookingApiApplication.java (needs Spring Boot)
package org.secondgear.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class BookingApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(BookingApiApplication.class, args);
    }
}

@RestController
class HelloController {
    record Hello(String shop, boolean open) {}

    @GetMapping("/api/v1/hello")
    Hello hello() {
        return new Hello("Second Gear Cycles", true);
    }
}

What this code does

@SpringBootApplication turns on component scanning from this package down, auto-configuration and the application's own configuration in one annotation. The controller method returns a record, and Spring MVC uses Jackson to write it as the same JSON object the hand-made server sent. There is no server code at all: the web starter's auto-configuration starts an embedded Tomcat on port 8080.

Running the application prints Spring's start-up log. The lines are worth reading once, because each names a piece of what Boot set up. The output below is representative of a Spring Boot 4.1 application on Java 25; the exact versions, timings and process number will differ on your machine.

Representative start-up log
./gradlew bootRun
Output
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v4.1.1)

INFO  o.s.api.BookingApiApplication : Starting BookingApiApplication using Java 25.0.1 with PID 41872
INFO  o.s.api.BookingApiApplication : No active profile set, falling back to 1 default profile: "default"
INFO  o.s.b.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
INFO  o.a.catalina.core.StandardService : Starting service [Tomcat]
INFO  o.a.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/11.0.x]
INFO  o.s.b.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
INFO  o.s.api.BookingApiApplication : Started BookingApiApplication in 1.412 seconds (process running for 1.71)

What this code does

The bootRun task compiles the code and starts the application from the build, without packaging it first. The log shows Tomcat starting on port 8080 and the application starting in under two seconds. Pressing Ctrl+C stops it.

Representative response
curl -i http://localhost:8080/api/v1/hello
Output
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 12 Jan 2028 23:41:07 GMT

{"shop":"Second Gear Cycles","open":true}

What this code does

curl -i shows the status line and headers as well as the body. Spring set the Content-Type to application/json because the method returned an object rather than a string.

A request flowing left to right: a browser and the counter computer send HTTP requests to an embedded Tomcat server inside one Spring Boot JAR. Inside the JAR the request passes through the DispatcherServlet, then a controller, then a service, then a repository, and finally to a PostgreSQL database outside the JAR. The JSON response returns along the same path.
One request through a Spring Boot web service: embedded server, DispatcherServlet, controller, service, repository, database.

How auto-configuration decides

Auto-configuration sounds like magic, but it is ordinary code that runs at start-up. Each auto-configuration class is a normal Spring configuration class with conditions on it: create this bean only if a certain class is on the class path, only if a certain property is set, or only if the application has not already defined a bean of the same type. When Hamza adds the PostgreSQL driver and Spring Data JPA to the build, the data source auto-configuration sees them and builds a HikariCP pool from his spring.datasource settings. If he defines his own DataSource bean, the condition "no DataSource bean yet" fails and Boot backs off.

The example imitates that decision with plain Java. It checks whether certain classes can be loaded, which is how a class-path condition works, and whether a property is set, and it chooses which pieces to configure. The JDK's own HTTP client is always present, while the PostgreSQL driver is not part of the JDK, so the program reports what a real application with and without it would get.

Java Example · Main.java
import java.util.*;

public class Main {
    static boolean onClassPath(String className) {
        try {
            Class.forName(className, false, Main.class.getClassLoader());
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    static List<String> autoConfigure(Map<String, String> properties, Set<String> userBeans) {
        List<String> report = new ArrayList<>();
        if (onClassPath("java.net.http.HttpClient") && !userBeans.contains("HttpClient")) {
            report.add("HttpClient: created a default client");
        } else {
            report.add("HttpClient: skipped (user bean or class missing)");
        }
        if (onClassPath("org.postgresql.Driver") && properties.containsKey("spring.datasource.url")) {
            report.add("DataSource: created a pool for " + properties.get("spring.datasource.url"));
        } else {
            report.add("DataSource: skipped (driver class not found or no URL)");
        }
        String port = properties.getOrDefault("server.port", "8080");
        report.add("Web server: port " + port);
        return report;
    }

    public static void main(String[] args) {
        Map<String, String> props = Map.of("spring.datasource.url", "jdbc:postgresql://db/secondgear", "server.port", "9090");
        autoConfigure(props, Set.of()).forEach(System.out::println);
        System.out.println("---");
        autoConfigure(Map.of(), Set.of("HttpClient")).forEach(System.out::println);
    }
}
Output
HttpClient: created a default client
DataSource: skipped (driver class not found or no URL)
Web server: port 9090
---
HttpClient: skipped (user bean or class missing)
DataSource: skipped (driver class not found or no URL)
Web server: port 8080

What this code does

Class.forName with false as its second argument checks that a class can be found without running its static initializer, which is how a class-path test can be cheap and safe. The first run has the URL but no driver on this class path, so the data source is skipped, and server.port overrides the default. The second run defines its own HttpClient bean, so the default one backs off, just as Spring Boot's conditions do.

When you want to know why Boot did or did not configure something, start the application with the --debug option or set debug=true in its properties. Boot then prints the condition evaluation report, which lists every auto-configuration with the conditions that matched and the ones that did not. The Actuator's conditions endpoint, covered in lesson 11, shows the same report from a running application.

The pieces you will meet this term

Hamza drew the plan for the term on the whiteboard, and Ingrid added a rule beside it: keep the web layer thin. A controller receives HTTP requests, checks their shape and translates them into calls on a service, which holds the business rules, such as how many repairs fit into an hour on a Saturday. The service uses repositories to read and write the database and clients to call other services, such as a supplier's price list. Each layer depends only on the one below it, through interfaces, which is the same idea as the ports and adapters Hamza is drawing in his Tuesday course: the web controller is simply one more adapter on the booking ports.

Try it yourself

Choose a configuration

pickStore should return postgres when the properties contain spring.datasource.url, and memory otherwise, but a user-supplied store (the userStore argument, when not null) always wins.

Print the result of the three calls in main, one per line.

import java.util.*;

public class Main {
    static String pickStore(Map<String, String> props, String userStore) {
        return "memory";
    }

    public static void main(String[] args) {
        System.out.println(pickStore(Map.of("spring.datasource.url", "jdbc:postgresql://db/secondgear"), null));
        System.out.println(pickStore(Map.of(), null));
        System.out.println(pickStore(Map.of("spring.datasource.url", "jdbc:postgresql://db/secondgear"), "test-fake"));
    }
}

Try it yourself

Answer a second path

The server answers /api/v1/hello. Add a context for /api/v1/hours that answers 200 with the body Tue-Sat 10:00-18:00.

The program then prints the status and body of both requests.

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;

public class Main {
    static void reply(com.sun.net.httpserver.HttpExchange ex, int status, String text) throws java.io.IOException {
        byte[] body = text.getBytes(StandardCharsets.UTF_8);
        ex.sendResponseHeaders(status, body.length);
        try (var out = ex.getResponseBody()) { out.write(body); }
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/api/v1/hello", ex -> reply(ex, 200, "hello"));
        server.start();
        try {
            String base = "http://127.0.0.1:" + server.getAddress().getPort();
            HttpClient client = HttpClient.newHttpClient();
            for (String path : new String[] {"/api/v1/hello", "/api/v1/hours"}) {
                HttpResponse<String> r = client.send(HttpRequest.newBuilder(URI.create(base + path)).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println(path + " " + r.statusCode() + (r.statusCode() == 200 ? " " + r.body() : ""));
            }
        } finally {
            server.stop(0);
        }
    }
}

By half past eight the hello endpoint was running on Hamza's laptop, Odile had a list of the four questions the booking page would ask, and Ingrid had written the homework on the whiteboard: read the start-up log line by line and find out which auto-configuration created each piece.

Common mistakes

  • MistakeThinking Spring Boot is a different framework from Spring.

    InsteadBoot is Spring with starters, auto-configuration and an embedded server added; the container and Spring MVC underneath are the same.

  • MistakeCreating helpers with new inside a service class.

    InsteadReceive them through the constructor so the container, or a test, can choose them.

  • MistakeCopying a Spring Boot version number from an old article.

    InsteadCheck the current release on the Spring website; minor versions arrive about every six months.

  • MistakeFighting auto-configuration with exclusions as a first step.

    InsteadDefine your own bean; Boot backs off when it finds one.

  • MistakePutting business rules in the controller.

    InsteadKeep controllers thin and put rules in services that can be tested without HTTP.

Summary and key terms

  • A web service answers HTTP requests with data, usually JSON, and REST services expose resources named by URLs and acted on with GET, POST, PUT, PATCH and DELETE.
  • The JDK includes an HTTP client and a small HTTP server, enough for a one-file service.
  • The Spring Framework provides an inversion of control container that creates and wires objects, plus Spring MVC and other modules.
  • Spring Boot adds starters, auto-configuration and an embedded server, so an application is one executable JAR.
  • Spring Boot 4 arrived in November 2025 with Spring Framework 7, needs Java 17 or later, uses Jakarta EE 11 and Jackson 3, and has new minor versions about every six months.
  • Auto-configuration is conditional configuration that backs off when the application defines its own beans; the condition evaluation report explains its choices.
  • A well-shaped service has thin controllers, services for rules, and repositories and clients behind interfaces.
Web service
A program that answers HTTP requests from other programs with data.
REST
A style of web service built around resources named by URLs and the standard HTTP methods.
Status code
The three-digit number in an HTTP response that says how the request went, such as 200, 201, 404 or 409.
Inversion of control
Letting a container create objects and pass them their dependencies instead of each object creating its own.
Application context
Spring's container, which holds the application's beans.
Starter
A Spring Boot dependency that brings in a tested set of libraries for one job.
Auto-configuration
Spring Boot code that configures beans at start-up based on the class path and properties, backing off when the application defines its own.
Embedded server
A web server, such as Tomcat, packaged inside the application JAR.
Spring Initializr
The start.spring.io tool that generates a new Spring Boot project.
Condition evaluation report
The start-up report that lists which auto-configurations applied and why.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which HTTP method creates a new booking?

    Show answer

    POST.

  2. What three things does Spring Boot add to the Spring Framework?

    Show answer

    Starters, auto-configuration and an embedded server.

  3. Why bind a test server to port 0?

    Show answer

    The operating system then picks any free port, so the program never clashes with another.

  4. What happens to an auto-configured bean when you define your own bean of the same type?

    Show answer

    The auto-configuration backs off and uses yours.

  5. Which Java version does Spring Boot 4 need at least?

    Show answer

    Java 17.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz