Skip to lesson

What Spring Boot will do for you next

You wrote routing, JSON, error mapping, wiring and threads by hand, and none of it is special to ShopLite. Every new API would need the same code again. Spring Boot supplies it, so you write only the part that sells products.

Everything we wrote by hand: routing, JSON, errors, wiring, threads, config

Plumbing is the code every API needs no matter what it sells: starting a server, matching method and path, reading and writing JSON, mapping errors to statuses, wiring objects, choosing threads, reading settings and stopping cleanly.

Example 1 counts the lines of each job in the HTTP package of shoplite-http.

Example 1 · The HTTP package of shoplite-http, by job

Text
shoplite-http/src/main/java/com/shoplite/http   (lines)  Routing      Router.java 122, ApiHandler 8, Request 43, Response 19  JSON         Json.java 88, JsonBody 37  Errors       ErrorMapper 54, ApiException 56, Problem 13, ProblemType 40,               FieldError 5, FieldErrors 40  Query/paging QueryParams 91, PageParams 40, PageResponse 16  Endpoints    ProductHandler 104, ProductRequest 76, ProductResponse 14,               CategoryHandler 64, CategoryRequest 22, CategoryResponse 11  Wiring, threads, config, stop               ShopLiteServer 101, ServerSettings 29  Total        1093 lines, about 60% of them plumbing every API needs
Summary
Plumbing (same in every API): Router, Request, Response, Json, JsonBody,
  ErrorMapper, ApiException, Problem, ProblemType, FieldErrors,
  QueryParams, PageParams, PageResponse, ShopLiteServer, ServerSettings
ShopLite-specific: ProductHandler, ProductRequest, ProductResponse,
  CategoryHandler, CategoryRequest, CategoryResponse
Unchanged from Section 13: model, dao, service, config

What this code does

  • Line counts are from the project of this module. Routing, JSON, errors, paging, wiring and settings are plumbing; only the six product and category classes are about ShopLite.
  • The model, dao, service and config packages are not in this list at all: they came from Section 13 and serve every front end.

In shoplite-http, plumbing is about 60% of the HTTP package. None of it is ShopLite-specific: a bank API or a college library API would need the same Router, Json and ErrorMapper, almost line for line, and each copy would need the same tests and bug fixes.

That is the problem a framework solves: it gives you well-tested plumbing, so you only write the handlers, the request and response records, and the rules.

The Spring Boot piece that replaces each one

Spring Boot is a framework that starts a web server for you (Tomcat by default), finds your classes and wires them, and connects them to HTTP through annotations.

Example 2 lists each hand-written piece of this module next to the Spring Boot feature that replaces it.

Example 2 · Hand-written piece → Spring Boot piece

Text
What we wrote by hand              Spring Boot piece that replaces it---------------------------------  ------------------------------------------------HttpServer.create + start          embedded Tomcat, started by SpringApplication.runRouter, {id} templates, 404/405    @RestController, @GetMapping("/{id}"), @PathVariableQueryParams, PageParams            @RequestParam, Pageable (Section 16)Json.readObject, strict mapper     @RequestBody + Jackson message convertersJson.write, Content-Type, length   return a record; Spring writes JSON and the headers415 check                          consumes = "application/json" (automatic for @RequestBody)FieldErrors, validate()            Bean Validation: @Valid, @NotBlank, @Size, @PositiveErrorMapper + catch-all            @RestControllerAdvice + @ExceptionHandler -> ProblemDetailShopLiteServer.start (wiring)      component scanning + constructor injection of beansExecutors.newFixedThreadPool       Tomcat thread pool (200 threads by default);                                   spring.threads.virtual.enabled=true on Java 21ServerSettings, AppConfig          application.properties, @ConfigurationPropertiesDataSourceFactory (HikariCP)       spring.datasource.* -> a HikariCP pool, auto-configuredshutdown hook + stop(5)            server.shutdown=graceful
Summary
Every row is the same job; only who writes the code changes.

What this code does

  • Each left-hand item is a class or method from this module; each right-hand item is the Spring Boot feature that does that job, often with one annotation or one property.
  • Pageable is taught with Spring Data in Section 16; the other rows come in the Spring Boot section.

Routing becomes @RestController with @GetMapping("/{id}") and @PathVariable; JSON in and out becomes @RequestBody and plain return values; the error mapper becomes @RestControllerAdvice returning ProblemDetail; wiring becomes component scanning with constructor injection; threads, the connection pool and settings come from application.properties.

The Spring Boot section teaches each of these in detail. For now, read the table as "the same job, done for you".

The same endpoint written both ways

@RestController marks a class whose methods answer HTTP requests. Annotations such as @GetMapping choose the method and path, and the returned object is written as JSON.

Examples 3 and 4 show GET /api/v1/products/{id} written for the JDK server and for Spring Boot.

Example 3 · HttpServer version: route and handler

Runs in: the shoplite-http project of this module (a fragment of ProductHandler.java)

Java
router.get("/api/v1/products/{id}", this::get);
private Response get(Request request) {    return Response.ok(ProductResponse.from(catalog.findProductView(request.pathId("id"))));}
Sample output
$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2026 06:49:41 GMT
Content-type: application/json
Content-length: 135

{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404 Not Found
Date: Fri, 16 Oct 2026 06:49:42 GMT
Content-type: application/problem+json
Content-length: 166

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Product 99 was not found.","instance":"/api/v1/products/99"}

What this code does

  • The route line and the handler method are the only endpoint-specific code. Matching the path, parsing the id, writing JSON and mapping errors live in the shared Router, Json and ErrorMapper classes you wrote in the earlier lessons.
  • The curl output is the real JDK server: HTTP/1.1 200 OK, header names as the JDK writes them, and the contract's Problem Details for product 99.

Example 4 · Spring Boot version: ProductController.java

Runs in: a Spring Boot 4.1 project (spring-boot-starter-webmvc and spring-boot-starter-jdbc) with the ShopLite model, dao and service packages copied in

ProductController.javaJava
package com.shoplite.web;
import com.shoplite.service.CatalogService;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/products")public class ProductController {
    private final CatalogService catalog;
    public ProductController(CatalogService catalog) {     // Spring passes the bean in        this.catalog = catalog;    }
    @GetMapping("/{id}")    public ProductResponse get(@PathVariable int id) {        return ProductResponse.from(catalog.findProductView(id));    }}
// ApiErrors.javapackage com.shoplite.web;
import com.shoplite.service.NotFoundException;import java.net.URI;import org.springframework.http.HttpStatus;import org.springframework.http.ProblemDetail;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvicepublic class ApiErrors {
    @ExceptionHandler(NotFoundException.class)    public ProblemDetail notFound(NotFoundException e) {        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());        problem.setType(URI.create("https://shoplite.example/problems/not-found"));        problem.setTitle("Resource not found");        return problem;    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 200 
Content-Type: application/json
Content-Length: 135
Date: Fri, 16 Oct 2026 06:49:44 GMT

{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404 
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:49:46 GMT

{"detail":"Product 99 was not found.","instance":"/api/v1/products/99","status":404,"title":"Resource not found","type":"https://shoplite.example/problems/not-found"}

What this code does

  • @GetMapping("/{id}") with @PathVariable int id replaces the route, the pattern and the parse; returning the record replaces Json.write. The constructor receives CatalogService from Spring.
  • @RestControllerAdvice is Spring's error mapper: NotFoundException becomes a ProblemDetail with the contract's type and title. The bodies match the JDK server; Tomcat omits the reason phrase and orders the problem fields alphabetically.

On the JDK server the endpoint is a route line, a three-line handler method, and about 300 lines of Router, Json and ErrorMapper behind them. In Spring Boot it is one annotated method that returns the same ProductResponse record, plus a small advice class that turns NotFoundException into the same Problem Details body. The CatalogService call in the middle is identical.

The responses are the same JSON; only details that belong to the server differ: Tomcat writes Content-Type with a capital T, omits the reason phrase (HTTP/1.1 200), and sorts the ProblemDetail fields alphabetically. A client that follows the contract does not care about any of these.

What stays the same: your services, DTOs and API design

An API contract is the written list of URLs, methods, status codes, JSON fields and error bodies that clients can rely on, here API-DESIGN.md. It does not depend on which server code implements it.

Example 5 runs the unchanged Section 13 service inside Spring Boot as a bean.

Example 5 · ShopLiteApplication.java: the same service as a bean

Runs in: a Spring Boot 4.1 project (spring-boot-starter-webmvc and spring-boot-starter-jdbc) with the ShopLite model, dao and service packages copied in

ShopLiteApplication.javaJava
package com.shoplite.web;
import com.shoplite.dao.Database;import com.shoplite.dao.JdbcCategoryDao;import com.shoplite.dao.JdbcProductDao;import com.shoplite.service.CatalogService;import javax.sql.DataSource;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;
@SpringBootApplicationpublic class ShopLiteApplication {
    public static void main(String[] args) {        SpringApplication.run(ShopLiteApplication.class, args);    }
    /** The same Section 13 service, built from the DataSource Spring Boot created. */    @Bean    CatalogService catalogService(DataSource dataSource) {        Database db = new Database(dataSource);        return new CatalogService(new JdbcCategoryDao(db), new JdbcProductDao(db));    }}
Sample output
o.s.boot.tomcat.TomcatWebServer          : Tomcat started on port 8080 (http) with context path '/'
com.shoplite.web.ShopLiteApplication     : Started ShopLiteApplication in 9.92 seconds

What this code does

  • SpringApplication.run replaces ShopLiteServer.main: it starts Tomcat, creates a HikariCP DataSource from spring.datasource.* properties, and builds every bean.
  • The @Bean method wires the unchanged Section 13 classes: Database, the two JDBC DAOs and CatalogService. Nothing in the service layer knows it now runs inside Spring.

The business layer does not move: CatalogService, its rules and exceptions, the DAOs and the model records are copied into the Spring Boot project unchanged, and one @Bean method builds the service. The request and response DTOs (records such as ProductResponse) stay too.

The contract stays exactly as designed: the same URLs under /api/v1, the same status codes, the same JSON fields and the same Problem Details. Changing the front door, from console to HttpServer to Spring Boot, touched only the outer layer each time.

Why learning the hard way makes framework errors easier to debug

A framework is a library that calls your code instead of being called by it: it owns the plumbing (server, routing, JSON, errors, threads) and runs your handlers at the right moment. Its errors still describe that plumbing.

Example 6 shows three Spring errors that you already understand from this module.

Example 6 · Spring Boot errors, read with this module in mind

Text
What you see in Spring Boot                              What it is, from this module---------------------------------------------------------  ----------------------------------------Web server failed to start. Port 8080 was already in use.   BindException: Address already in use405 + Allow: GET (for DELETE /api/v1/products/1)            the Router's 405 with an Allow header400 for GET /api/v1/products/abc                            Spring could not convert "abc" to int for                                                            @PathVariable int id (we chose 404)415 for a text/plain body on a @RequestBody endpoint        the Content-Type check before parsingHttpMessageNotReadableException -> 400                      Jackson could not read the body: malformedMethodArgumentNotValidException -> 400                      @Valid failed: our validation-failedNoResourceFoundException -> 404                             no route matched the pathan unhandled exception -> 500                               the catch-all; the cause is in the logHTTP/1.1 200 (no "OK")                                      Tomcat, like the JDK for 422, omits the phrase
Sample output
$ curl -i -X DELETE http://localhost:8080/api/v1/products/1     (Spring Boot)
HTTP/1.1 405
Allow: GET
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:49:47 GMT

{"timestamp":"2026-10-16T06:49:47.530Z","status":405,"error":"Method Not Allowed","path":"/api/v1/products/1"}
$ curl -i http://localhost:8080/api/v1/products/abc            (Spring Boot)
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:49:48 GMT
Connection: close

{"timestamp":"2026-10-16T06:49:48.066Z","status":400,"error":"Bad Request","path":"/api/v1/products/abc"}
$ java -jar target/boot-compare-1.0.0.jar                       (a second copy)
***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

What this code does

  • Every Spring error on the left is one you met by hand. The real outputs show Spring's 405 with Allow, its 400 for a path variable that is not a number, and its port-in-use message.
  • Notice the default error body {"timestamp","status","error","path"}: it is not the contract's Problem Details. The Spring Boot section configures that, and you now know why it matters.

"Port 8080 was already in use" is the BindException from the first lesson. A 405 with Allow: GET is the router rule you wrote. A 400 for /products/abc happens because Spring could not turn abc into the int parameter, the same parse you guarded with a pattern.

When something breaks, ask: did the request reach a route, was the body read as JSON, which exception was thrown and how was it mapped, is a thread or a database connection waiting? The defaults differ in places: out of the box, Spring Boot answers some errors with its own {"timestamp", "status", "error", "path"} body instead of Problem Details. Knowing the contract, you will notice and configure it, which the Spring Boot section does.

Next step

Check your understanding

10 quick questions