Bookmarks
ReferenceBackendVerified

Java and Spring

Java and Spring — the language and ecosystem for server-side applications. In this reference: Spring Boot, beans and dependency injection, REST, JPA, tests, Spring Security.

checked 1 Nov · next check 8 Nov · 49 min read

Sections
13
Reading
49 min
Current version
4.1.2
Written from
docs.spring.io/spring-boot

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Java and Spring are and how they work

Java is a language for the Java Virtual Machine (JVM): javac compiles .java files into .class bytecode, and the JVM executes it with JIT compilation and garbage collection. Spring is a family of projects for server-side Java applications: its foundation, Spring Framework, creates and wires the application’s objects, while Spring Boot configures them automatically and runs them with an embedded server.

Spring is the usual choice for services that live for years and grow with the team: REST APIs, internal enterprise systems, integrations, batch data processing. Modules are added as needed — web, data access, transactions, security, messaging. Ready-made dependency bundles are called starters, for example spring-boot-starter-webmvc for web. Spring also works with other JVM languages such as Kotlin and Groovy. For a short script or a command-line utility it is usually unnecessary: such programs need neither an IoC container nor a web server.

Every HTTP request in a Spring Boot application follows the same path. The embedded server accepts the connection, and filters — including the Spring Security filters — examine the request. DispatcherServlet, the single entry point of Spring MVC, then finds the right controller method. The controller calls a service, the service calls a repository, and Spring MVC turns the object returned by the controller into JSON.

Without the Spring Security starter there is no layer of filters; the controller, service and repository are your own classes, which Spring creates itself.
  1. Embedded Tomcat accepts the connection (by default on port 8080) and passes the request to the servlet filter chain.
  2. The Spring Security filters check who sent the request and whether it may pass. A filter can answer on its own, and then the request goes no further.
  3. DispatcherServlet uses annotations such as @GetMapping to find a handler method and invoke it.
  4. The controller hands the work to a service, and the service reads and writes data through a Spring Data repository.
  5. A message converter writes the object returned by the controller method into the response body as JSON using the Jackson library, and Tomcat sends the response to the client.

The main class and auto-configuration

The @SpringBootApplication annotation on the main class enables auto-configuration: Spring Boot looks at which libraries are among the dependencies and creates configured objects for them on its own. For example, if HSQLDB is among the dependencies and you have not declared your own DataSource, Spring Boot will start an embedded in-memory database. Any part can be replaced with your own configuration — the auto-configuration for that part then steps aside.

javaShopApplication.java
package com.example.shop; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplicationpublic class ShopApplication {     public static void main(String[] args) {        SpringApplication.run(ShopApplication.class, args);    }}

How Spring Boot differs from Spring Framework

AspectSpring FrameworkSpring Boot
Rolethe foundation: IoC container and dependency injection, Spring MVC, transactions, data accessa layer on top of Spring Framework: auto-configuration and running the application
Configurationyou describe the objects and the links between them yourselfobjects for the libraries it detects are created automatically; any of them can be replaced with your own
Web serverthe application is deployed into a servlet container, and DispatcherServlet is registered manuallythe server is embedded in the application; filters and servlets are registered from Spring configuration

Start with Spring Boot: the Spring Framework documentation recommends the same. Bare Spring Framework is needed when the application is deployed into a ready-made application server whose updates you do not control.

What to know beforehand

  • The Java that Spring uses: classes, record classes, generics, exceptions, lambdas — the section “The Java that Spring uses” in this reference.
  • HTTP: methods, response codes, headers — the HTTP and REST reference.
  • SQL basics: tables, keys, SELECT and JOIN — the SQL reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday commands, starters, annotations and properties; each line is explained in its own section. The examples use the shop project from the section “Installation and first run”, and shop.jar is shorthand for target/shop-0.0.1-SNAPSHOT.jar.

Build and run

TaskCommand
Run the application from source./mvnw spring-boot:run
The same in a Gradle project./gradlew bootRun
Build the executable jar./mvnw package
Build the jar with Gradle./gradlew bootJar
Run the built jarjava -jar shop.jar
Run on a different portjava -jar shop.jar --server.port=9090
Enable the prod profilejava -jar shop.jar --spring.profiles.active=prod
Run the tests./mvnw test
Auto-configuration conditions reportjava -jar shop.jar --debug
Build a container image./mvnw spring-boot:build-image

Starters

NeedStarter
A REST API on Spring MVC and Tomcatspring-boot-starter-webmvc
Input validationspring-boot-starter-validation
JPA, Hibernate and Spring Data repositoriesspring-boot-starter-data-jpa
Flyway schema migrationsspring-boot-starter-flyway
Spring Securityspring-boot-starter-security
Actuator: health and metricsspring-boot-starter-actuator
Tests: JUnit, AssertJ, Mockitospring-boot-starter-test
Spring MVC tests (@WebMvcTest)spring-boot-starter-webmvc-test

Annotations: components and web

TaskHow to write it
Main class: auto-configuration and scanning@SpringBootApplication
A custom component for scanning@Component
A class with business logic@Service
A data-access class@Repository
A bean from a third-party class@Configuration and a method with @Bean
A REST controller with a base path@RestController and @RequestMapping("/api/products")
A method for GET /api/products/7@GetMapping("/{id}")
A value from the path@PathVariable long id
The ?page=2 parameter@RequestParam(defaultValue = "0") int page
A JSON request body with validation@Valid @RequestBody NewProduct body
A 201 Created response@ResponseStatus(HttpStatus.CREATED)

Annotations: data and tests

TaskHow to write it
A JPA entity@Entity, @Id, @GeneratedValue
A repositoryinterface ProductRepository extends JpaRepository<Product, Long>
A query derived from the method nameList<Product> findByPriceLessThan(BigDecimal max)
A custom JPQL query@Query("select p from Product p where p.name like %:text%")
A transaction boundary@Transactional on a service method
A test for a single controller@WebMvcTest(ProductController.class)
A test for repositories@DataJpaTest
A test of the whole application@SpringBootTest
Replace a bean with a Mockito mock@MockitoBean

Properties

TaskHow to write it
HTTP portserver.port=9090
Database URLspring.datasource.url=jdbc:postgresql://localhost:5432/shop
The database password from the environmentthe SPRING_DATASOURCE_PASSWORD variable
The active profilespring.profiles.active=prod
Only validate the database schemaspring.jpa.hibernate.ddl-auto=validate
Errors in Problem Details formatspring.mvc.problemdetails.enabled=true
Verbose logging for your own packagelogging.level.com.example.shop=debug
Which Actuator endpoints to exposemanagement.endpoints.web.exposure.include=health,info
Time to finish requestsspring.lifecycle.timeout-per-shutdown-phase=20s

Actuator

TaskAddress
Application health/actuator/health
Kubernetes probes/actuator/health/liveness, /actuator/health/readiness
Metrics/actuator/metrics
Metrics for Prometheus/actuator/prometheus
Where a property value came from/actuator/env
All controller mappings/actuator/mappings

Section sources

the section is written from these pages

Installation and first run

Spring Boot needs only the JDK, the Java development kit. Install JDK 25, create a project on start.spring.io and run it with ./mvnw spring-boot:run: the build tool wrapper in the project downloads Maven itself, so you do not need to install it separately.

Spring Boot 4.1 requires Java 17 or newer and works with versions up to and including Java 27. Among build tools, Maven 3.6.3 and newer and Gradle 8.14 and newer or 9.x are supported; among embedded servers, Tomcat 11.0 and Jetty 12.1. This reference uses JDK 25, a long-term support (LTS) release.

Linux

In Ubuntu 22.04, 24.04 and 26.04, JDK 25 is in the official repositories — the openjdk-25-jdk package:

bashon the host
sudo apt updatesudo apt install openjdk-25-jdk

For other distributions, Oracle ships the JDK as .deb and .rpm packages, a .tar.gz archive and packages in the Oracle Linux repositories; the installation guide is among the sources of this section.

macOS and Windows

Install JDK 25 with the official installer for your system. Spring Boot needs no special support from the IDE: the project opens in any Java IDE as an ordinary Maven or Gradle project.

A quick check

bashon the host
java -version
textexample output
openjdk version "25.0.x" ...OpenJDK Runtime Environment (build 25.0.x+...)OpenJDK 64-Bit Server VM (build 25.0.x+..., mixed mode, sharing)

The first project

The easiest way to create the project is Spring Initializr at start.spring.io: pick Maven, Java 25 and the Spring Web dependency, set the name shop and the package com.example.shop, download the archive and unpack it into a shop directory. This gives you the following tree:

text
shop/├── .gitattributes├── .gitignore├── .mvn/wrapper/maven-wrapper.properties├── HELP.md├── mvnw├── mvnw.cmd├── pom.xml└── src/    ├── main/    │   ├── java/com/example/shop/    │   │   └── ShopApplication.java    │   └── resources/    │       └── application.properties    └── test/java/com/example/shop/        └── ShopApplicationTests.java

mvnw and mvnw.cmd are the Maven wrapper for Linux, macOS and Windows; the .gitattributes and .gitignore files are prepared for a Git repository. pom.xml inherits from spring-boot-starter-parent: it manages the versions of Spring libraries and plugins, which is why the starters carry no version. The java.version property sets the Java version your code is compiled for.

xmlpom.xml, fragment
<properties>    <java.version>25</java.version></properties> <dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-webmvc</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-webmvc-test</artifactId>        <scope>test</scope>    </dependency></dependencies>

Add the other starters from this reference — Validation, Spring Data JPA, Actuator, Spring Security — as you need them: each section names the one it uses. Start with Spring Web alone and add your first controller next to ShopApplication.java:

javaHelloController.java
package com.example.shop; import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController; @RestControllerpublic class HelloController {     @GetMapping("/hello")    public String hello() {        return "Hello, Spring!";    }}

Run the application from the project directory:

bashin the shop directory
./mvnw spring-boot:run
textexample output
 :: Spring Boot ::  (v4.1.x)...Started ShopApplication in 1.9 seconds (process running for 2.2)

In another terminal, call the controller:

bashon the host
curl http://localhost:8080/hello
textexample output
Hello, Spring!

To stop the application, press Ctrl+C in the first terminal. In a Gradle project, ./mvnw spring-boot:run is replaced by ./gradlew bootRun.

Section sources

the section is written from these pages

Java for Spring

Reading and writing Spring code takes only a small part of Java: classes and interfaces, record classes for data, collections with generics, exceptions, lambdas and annotations. This is not a full language reference — only what comes up in every Spring project.

Classes, interfaces and packages

Java code lives in classes, classes live in packages, and a package mirrors the file path: the class com.example.shop.product.ProductService sits in src/main/java/com/example/shop/product/ProductService.java. An interface describes what an object can do, and a class with implements — how exactly. public is visible to all, private only inside the class, and a member without a modifier only within its own package.

javaGreeter.java, PoliteGreeter.java
public interface Greeter {    String greet(String name);} public class PoliteGreeter implements Greeter {     private final String prefix;     public PoliteGreeter(String prefix) {        this.prefix = prefix;    }     @Override    public String greet(String name) {        return prefix + ", " + name;    }}

A field with final receives its value once — in the constructor. This is how almost all dependencies of a class are declared in Spring code.

Record classes for data

A record class is a compact way to write a data-carrying class. The components are listed in the header, and the compiler generates the constructor, the accessor methods, equals, hashCode and toString itself. The fields of a record class are private final, which makes it a good fit for DTOs — the bodies of API requests and responses.

javaMoney.java
public record Money(BigDecimal amount, String currency) {     // compact constructor: validation before the fields are assigned    public Money {        if (amount.signum() < 0) {            throw new IllegalArgumentException("amount < 0");        }    }     public Money plus(Money other) {        return new Money(amount.add(other.amount), currency);    }}

The accessor methods are named after the components, without get: money.amount(), not getAmount(). The compact constructor is written without a parameter list: the compiler fills the parameters in from the header.

Generics and Optional

Generics are type parameters in angle brackets: List<Product> is a list of products, Map<String, Integer> a map with string keys, ResponseEntity<Product> a controller response with a product body (how responses work — in the section “Web and REST controllers”). The compiler keeps track of the types, and a string cannot end up in such a list. Optional<Product> is a container that may hold no value: findById in Spring Data returns it, and instead of checking for null you write orElseThrow() or map().

Collections

List.of, Set.of and Map.of create unmodifiable collections: an element cannot be added, removed or replaced, and null cannot be put into them. If a collection needs to be changed, copy it into a mutable one — ArrayList, HashSet or HashMap.

java
List<String> names = List.of("tea", "coffee", "milk");Map<String, Integer> stock = Map.of("tea", 5, "milk", 0); // List.of is unmodifiable: to change it, make a copyList<String> cart = new ArrayList<>(names);cart.add("sugar");
InterfaceWhat it storesMutable implementation
Listelements in order, duplicates allowedArrayList
Setelements without duplicatesHashSet
Map“key — value” pairs, keys without duplicatesHashMap

Exceptions

Exceptions are either checked or unchecked. The compiler requires a checked exception, such as IOException, to be caught in a catch block or declared in the method’s throws clause. RuntimeException, Error and their subclasses are exempt from this check. In Spring applications, business logic errors are usually made unchecked: such an exception travels from the service to the error handler without a throws in every method.

javaProductNotFoundException.java
public class ProductNotFoundException extends RuntimeException {     public ProductNotFoundException(long id) {        super("Product " + id + " not found");    }}

Try-with-resources closes the file, connection or stream itself when the block ends — even if an exception occurs inside:

java
static long countLines(Path file) throws IOException {    try (var lines = Files.lines(file)) {        return lines.count();    }}

Lambdas and the Stream API

A lambda is a compact way to write a function: name -> name.toUpperCase(). It is passed wherever an interface with a single abstract method is expected. The Stream API processes a collection as a chain of operations: intermediate operations (filter, map, sorted) describe the steps lazily, and a terminal operation (toList, count, collect) triggers the computation.

java
record Item(String name, BigDecimal price, String category) {} // items — a List<Item> with catalogue productsvar limit = new BigDecimal("10000");List<String> cheap = items.stream()        .filter(i -> i.price().compareTo(limit) < 0)        .map(Item::name)        .sorted()        .toList(); Map<String, Long> byCategory = items.stream()        .collect(Collectors.groupingBy(Item::category,                Collectors.counting()));
OperationWhat it does
filter(x -> …)keeps the elements for which the condition is true
map(x -> …)turns each element into another value
sorted()sorts; with a Comparator, in a custom order
distinct()removes duplicates
limit(n)takes the first n elements
toList()collects the result into an unmodifiable list
findFirst()the first element as an Optional
collect(Collectors.groupingBy(…))groups into a Map by key

var and pattern matching for switch

var infers the type of a local variable from the right-hand side: var request = PageRequest.of(0, 20);. switch supports pattern matching: the branch case Card c -> fires when the value is a Card and immediately gives the variable c, while the record class pattern Cash(int change) deconstructs the value into its components. For a sealed interface the compiler checks that every variant is listed, so default is not needed.

java
sealed interface Payment permits Card, Cash {} record Card(String number) implements Payment {} record Cash(int change) implements Payment {} static String describe(Payment payment) {    return switch (payment) {        case Card c -> "card " + c.number();        case Cash(int change) -> "cash, change " + change;    };}

Annotations

An annotation is a marker of the form @Name on a class, method, field or parameter. It does not run anything itself: @Override is checked by the compiler, while @Service, @GetMapping and @Transactional are read by Spring at startup: from them it creates the objects and routes, and wraps every call to a method with @Transactional in a transaction. An annotation can take parameters: @GetMapping("/{id}"), @Column(nullable = false).

Section sources

the section is written from these pages

Beans and dependency injection

A bean is an object that the Spring IoC container (ApplicationContext) creates and stores. A class does not build its dependencies with new — it receives them through its constructor, and the container assembles the objects in the right order on its own. This is dependency injection.

At startup Spring Boot scans the main class’s package and all nested packages. Classes carrying @Component, @Service, @Repository, @Controller and @RestController are registered as beans. The container then calls their constructors and passes each one already-created beans of the required types. For third-party classes that you cannot annotate — for example, Clock from the JDK — declare a bean with an @Bean method inside a @Configuration class. That is why the main class is kept in the project’s root package: scanning only goes downwards from it, through its package and the packages nested inside.

The container derives the creation order from the constructors: dependencies first, then the bean that waits for them.

Constructor injection

The recommended approach is to pass dependencies through the constructor and store them in final fields. With a single constructor @Autowired is not needed; with several, mark with @Autowired the one Spring should use.

javaProductService.java
@Servicepublic class ProductService {     private final ProductRepository products;    private final Clock clock;     // single constructor — no @Autowired needed    public ProductService(ProductRepository products, Clock clock) {        this.products = products;        this.clock = clock;    }     // ...}

Once the constructor has run, the object is fully ready, and a required dependency cannot turn out to be null. Such a class is testable without Spring too: in a test it is created with new and given stubs. Too many constructor parameters mean the class is doing too much and should be split up.

A bean from a foreign class: @Bean

javaClockConfig.java
@Configurationpublic class ClockConfig {     // Clock is a JDK class: declare the bean by hand    @Bean    public Clock clock() {        return Clock.systemUTC();    }}

An @Bean method returns an object, and the container registers it as a bean. Spring fills the method’s parameters with other beans — the same way as constructor parameters.

Scopes

By default a bean is a singleton: one object per container, shared by everyone who receives it. The documentation advises making stateless beans singletons and giving stateful beans the prototype scope.

ScopeObjects createdWhere it works
singleton (default)one per containereverywhere
prototypea new one on every injection or bean lookupeverywhere
requestone per HTTP requestin a web application
sessionone per HTTP sessionin a web application
applicationone per ServletContextin a web application
javaCsvReport.java
@Component@Scope("prototype")public class CsvReport {     private final List<String> rows = new ArrayList<>();     public void add(String row) {        rows.add(row);    }}

Several beans of the same type

When several beans match a dependency, Spring will not choose one itself. Mark the default bean with @Primary, and at the point where a different one is needed, name it in @Qualifier. Without annotations Spring picks the bean whose name matches the parameter name; to make the names available, compile the code with the -parameters flag.

javaPaymentConfig.java
@Configurationpublic class PaymentConfig {     @Bean    @Primary    public PaymentGateway cardGateway() {        return new CardGateway();    }     @Bean    public PaymentGateway cashGateway() {        return new CashGateway();    }}
javaCheckoutService.java
@Servicepublic class CheckoutService {     private final PaymentGateway gateway;     public CheckoutService(            @Qualifier("cashGateway") PaymentGateway gateway) {        this.gateway = gateway;    }}

Circular dependencies

If bean A waits for B in its constructor while B waits for A, the container cannot create either and throws BeanCurrentlyInCreationException at startup. A cycle usually means responsibility is divided badly: move the shared part into a third bean that both of them depend on.

Section sources

the section is written from these pages

Configuration and profiles

Spring Boot takes settings from several sources: application.properties or application.yaml files, profile-specific files, environment variables and command-line arguments. A source with higher priority overrides the rest, so one and the same jar runs in dev and production with different values.

The order of the sources is fixed. At the bottom are the files inside the jar, above them the files next to the jar. Higher still come environment variables and Java system properties, and at the very top, command-line arguments. If server.port is set in several places, the value from the highest source wins.

The main sources are shown here; among the others are, for example, SPRING_APPLICATION_JSON and test properties.
propertiesapplication.properties
spring.application.name=shopserver.port=8080spring.datasource.url=jdbc:postgresql://localhost:5432/shopspring.datasource.username=shopshop.currency=UZSshop.page-size=20

The same settings in YAML are written as nested keys. Keep one format per project: if .properties and .yaml files sit side by side, .properties takes priority.

yamlapplication.yaml
spring:  application:    name: shop  datasource:    url: jdbc:postgresql://localhost:5432/shopshop:  currency: UZS

Environment variables

A property name turns into an environment variable name by three rules: dots become underscores, hyphens are removed, letters become uppercase. This is how settings are passed to a container or a cloud platform without changing the files in the jar.

PropertyEnvironment variable
spring.datasource.urlSPRING_DATASOURCE_URL
spring.profiles.activeSPRING_PROFILES_ACTIVE
server.portSERVER_PORT
shop.page-sizeSHOP_PAGESIZE
spring.main.log-startup-infoSPRING_MAIN_LOGSTARTUPINFO
bashon the server
export SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/shopexport SPRING_DATASOURCE_PASSWORD=change-mejava -jar target/shop-0.0.1-SNAPSHOT.jar

Profiles

A profile is a named set of settings for one environment. The values from application-prod.properties apply only when the prod profile is active, and they override the common application.properties. If several profiles are active, the one named last wins. When none is enabled, the default profile is in effect.

propertiesapplication-prod.properties
spring.jpa.hibernate.ddl-auto=validatelogging.level.root=warnmanagement.endpoints.web.exposure.include=health,prometheus
bashon the server
# as a command-line argumentjava -jar target/shop-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod# or as an environment variableSPRING_PROFILES_ACTIVE=prod java -jar target/shop-0.0.1-SNAPSHOT.jar

spring.profiles.active must not be set in a profile-specific file itself: Spring Boot treats such a document as invalid. A bean or @Configuration class is enabled only in the required environment with the @Profile("prod") annotation.

Typed settings: @ConfigurationProperties

Custom settings are easier to read not one by one but as a group — into a record class. The shop prefix binds the shop.currency and shop.page-size properties to the currency and pageSize components: in the file the names are written with a hyphen, and Spring Boot matches them itself (relaxed binding). With @Validated the values are checked at startup, and with a wrong setting the application does not start.

javaShopProperties.java
@Validated@ConfigurationProperties("shop")public record ShopProperties(        @NotBlank String currency,        @DefaultValue("20") @Max(100) int pageSize) {}

For Spring Boot to find such classes, add @ConfigurationPropertiesScan to the main class or list them in @EnableConfigurationProperties. ShopProperties is then injected into a constructor like any bean.

javaShopApplication.java
@SpringBootApplication@ConfigurationPropertiesScanpublic class ShopApplication {    // ...}

If a value fails validation, for example --shop.page-size=500, the application stops at startup:

textexample output
***************************APPLICATION FAILED TO START*************************** Description: Binding to target com.example.shop.ShopProperties failed:     Property: shop.pageSize    Value: "500"    Origin: "shop.page-size" from property source "commandLineArgs"    Reason: must be less than or equal to 100 Action: Update your application's configuration

A single value: @Value

For a single value, @Value with a placeholder is enough; after the colon comes the default value:

javaSupportInfo.java
public SupportInfo(        @Value("${shop.email:help@example.com}") String email) {    this.email = email;}

Passwords and keys

propertiesapplication.properties
# the file with passwords sits next to the jar and is not kept in Gitspring.config.import=optional:file:./secrets.properties

The optional: prefix allows starting without this file; without the prefix, a missing file stops the startup with ConfigDataLocationNotFoundException.

Section sources

the section is written from these pages

Web and REST controllers

A REST controller is a class with @RestController whose methods answer HTTP requests. An annotation such as @GetMapping("/{id}") binds a method to an HTTP method and a path; the method parameters take data from the path, the query string and the body, and the returned object becomes the response body.

javaProductController.java
@RestController@RequestMapping("/api/products")public class ProductController {     private final ProductService service;     public ProductController(ProductService service) {        this.service = service;    }     @GetMapping    public List<ProductView> list(            @RequestParam(defaultValue = "0") int page,            @RequestParam(defaultValue = "20") int size) {        return service.list(page, size);    }     @GetMapping("/{id}")    public ProductView get(@PathVariable long id) {        return service.get(id);    }     @PostMapping    @ResponseStatus(HttpStatus.CREATED)    public ProductView create(@Valid @RequestBody NewProduct body) {        return service.create(body);    }     @DeleteMapping("/{id}")    @ResponseStatus(HttpStatus.NO_CONTENT)    public void delete(@PathVariable long id) {        service.delete(id);    }}

@RequestMapping on the class sets a common path prefix, and @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping on methods set the HTTP method and the rest of the path. The value from {id} lands in the parameter annotated with @PathVariable and is converted to its type: on /api/products/abc a long parameter cannot be filled, and the client gets a 400 response.

AnnotationWhere the value comes fromExample
@PathVariablefrom the path/api/products/7 → id = 7
@RequestParamfrom the query string or form data?page=2 → page = 2
@RequestBodyfrom the request body, usually JSON{"name": "Tea", "price": 12000} → NewProduct

Query parameters

A @RequestParam parameter is required by default. Make it optional with required = false or the Optional type; defaultValue sets a default value. The List type collects all repetitions of the parameter: ?tag=new&tag=sale. Spring also reads simple parameters without an annotation as @RequestParam — from the query string and from form data ([[application/x-www-form-urlencoded]]) alike.

javaSearchController.java
@GetMapping("/api/search")public List<String> search(        @RequestParam String q,        @RequestParam(required = false) List<String> tag) {    // ...}

Request body and validation

@RequestBody turns the JSON from the request body into an object — most conveniently into a record class. Constraint annotations from jakarta.validation.constraints set the rules, and @Valid on a parameter switches validation on. The check is performed by Hibernate Validator, which comes with the spring-boot-starter-validation starter.

javaNewProduct.java
public record NewProduct(        @NotBlank @Size(max = 100) String name,        @NotNull @Positive BigDecimal price) {}

If the data fails validation, the controller method is not called: Spring MVC throws MethodArgumentNotValidException and responds with 400 (Bad Request).

bashon the host
curl -i http://localhost:8080/api/products \  -H 'Content-Type: application/json' \  -d '{"name": "", "price": -5}'
textexample output
HTTP/1.1 400Content-Type: application/problem+json... {  "detail": "Invalid request content.",  "instance": "/api/products",  "status": 400,  "title": "Bad Request"}

Response status

A successful response is 200 OK by default. @ResponseStatus(HttpStatus.CREATED) changes it to 201 for creation, and HttpStatus.NO_CONTENT (204) suits deletion without a body. When the code or the headers depend on the data, return a ResponseEntity, for example ResponseEntity.notFound().build(). Which code to use in which situation is covered in the HTTP and REST reference, in the section “Status codes”.

Errors in the Problem Details format

Problem Details (RFC 9457) is a standard JSON format for HTTP API errors, with the fields type, title, status, detail and instance. The property spring.mvc.problemdetails.enabled=true switches this format on for the built-in Spring MVC errors: invalid JSON, failed validation, a missing parameter. Convert your own exceptions into a ProblemDetail in an @ExceptionHandler method in a class with @ControllerAdvice.

propertiesapplication.properties
spring.mvc.problemdetails.enabled=true
javaApiErrors.java
@ControllerAdvicepublic class ApiErrors {     @ExceptionHandler    public ProblemDetail notFound(ProductNotFoundException ex) {        return ProblemDetail.forStatusAndDetail(                HttpStatus.NOT_FOUND, ex.getMessage());    }}
textexample output
HTTP/1.1 404Content-Type: application/problem+json... {  "detail": "Product 999 not found",  "instance": "/api/products/999",  "status": 404,  "title": "Not Found"}

The messages of built-in errors should not go to the client as they are: they may contain implementation details. The title and detail texts are overridden in messages.properties under keys like problemDetail.title.<fully qualified exception class name>.

The RestClient HTTP client

When a controller needs to call a third-party REST API itself, Spring offers RestClient, a synchronous HTTP client with a fluent, chainable API ([[fluent API]]): RestClient.create().get().uri("https://example.com/products").retrieve().body(ProductView.class).

Section sources

the section is written from these pages

Data: Spring Data JPA

Spring Data JPA builds a repository implementation from an interface: interface ProductRepository extends JpaRepository<Product, Long> can already save, find and delete, and methods such as findByPriceLessThan turn into queries built from the name. JPA and Hibernate do the work underneath.

Connecting to the database

The spring-boot-starter-data-jpa starter brings in Hibernate, Spring Data JPA and the HikariCP connection pool; you add the database driver yourself. The address and the credentials are set by the spring.datasource.* properties. Without spring.datasource.url Spring Boot tries to bring up an embedded database (H2, HSQL), and if it is not among the dependencies the application fails to start.

xmlpom.xml, fragment
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency>    <groupId>org.postgresql</groupId>    <artifactId>postgresql</artifactId>    <scope>runtime</scope></dependency>
propertiesapplication.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/shopspring.datasource.username=shop# the password goes in the SPRING_DATASOURCE_PASSWORD variablespring.datasource.hikari.maximum-pool-size=10

The entity

An entity is a class marked with @Entity whose objects correspond to table rows. @Id marks the primary key, and @GeneratedValue leaves issuing the key to the database. Spring Boot looks for entities in the main class’s package and below; the persistence.xml file is not needed. JPA requires a no-argument constructor — make it protected so that your own code does not use it.

javaProduct.java
@Entitypublic class Product {     @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;     @Column(nullable = false, length = 100)    private String name;     @Column(nullable = false)    private BigDecimal price;     private Instant createdAt;     @ManyToOne(fetch = FetchType.LAZY)    private Category category;     // required by JPA, not used by your code    protected Product() {    }     public Product(String name, BigDecimal price, Instant createdAt) {        this.name = name;        this.price = price;        this.createdAt = createdAt;    }     public Long getId() {        return id;    }     // remaining getters and setters}

The repository and query methods

javaProductRepository.java
public interface ProductRepository        extends JpaRepository<Product, Long> {     Optional<Product> findByNameIgnoreCase(String name);     List<Product> findByPriceBetween(BigDecimal min, BigDecimal max);     Page<Product> findByPriceLessThan(BigDecimal max, Pageable page);     boolean existsByNameIgnoreCase(String name);     List<Product> findTop5ByOrderByPriceDesc();     @Query("select p from Product p where p.name like %:text%")    List<Product> search(String text);     @Modifying    @Query("update Product p set p.price = p.price * :factor")    int changeAllPrices(BigDecimal factor);}

A method name is parsed into two parts. Before By — what to do: find, exists, count, delete. After it — the condition on the entity’s properties. The methods findById, findAll, save, deleteById and count already exist in JpaRepository.

In the method nameConditionExample
And, Orboth conditions or any of themfindByNameAndPrice
Betweenthe value is within a rangefindByPriceBetween(min, max)
LessThan, GreaterThanless than or greater thanfindByPriceLessThan(max)
Likean SQL LIKE patternfindByNameLike("%tea%")
IgnoreCasecase-insensitivefindByNameIgnoreCase(name)
OrderBy…Asc, OrderBy…DescsortingfindByPriceLessThanOrderByNameAsc
Top, Firstonly the first N rowsfindTop5ByOrderByPriceDesc()

Your own query: @Query

When a method name gets too long, write a JPQL query in @Query. JPQL works with entities and their fields (Product p, p.price), not with tables. The named parameter :text is bound to the method parameter by name: if the code was compiled with the -parameters flag (as spring-boot-starter-parent does), @Param is not needed. A query that changes data is marked with @Modifying.

Pages and sorting

A Pageable parameter adds pagination: PageRequest.of(0, 20, Sort.by("name")) is the first page with 20 rows on it, sorted by name. Page knows the total number of rows and makes an extra count query for that; if you do not need this number, return a Slice or a List.

java
var page = products.findByPriceLessThan(        new BigDecimal("50000"),        PageRequest.of(0, 20, Sort.by("name")));long total = page.getTotalElements();List<Product> items = page.getContent();

Transactions

The methods of JpaRepository already run inside a transaction: reads with readOnly = true, writes in a regular one. But if a service calls several repository methods in a row, each runs in its own transaction. Declare the boundary where the operation begins — on the service method, with @Transactional. Your own @Query methods do not get a transaction by default.

javaProductService.java
@Transactionalpublic ProductView create(NewProduct request) {    var product = new Product(request.name(), request.price(),            Instant.now(clock));    return ProductView.of(products.save(product));} @Transactionalpublic int raisePrices(BigDecimal factor) {    return products.changeAllPrices(factor);}

The database schema: Flyway instead of ddl-auto

The spring.jpa.hibernate.ddl-auto property lets Hibernate build tables from the entities. The values are none, validate, update, create, create-drop. For an embedded database without Flyway and Liquibase the default is create-drop, otherwise it is none: on PostgreSQL the tables will not appear on their own.

For Flyway, add spring-boot-starter-flyway and the module for your database — for PostgreSQL that is org.flywaydb:flyway-database-postgresql. Migrations are SQL files such as V1__create_product.sql in src/main/resources/db/migration; Flyway applies the new ones when the application starts. The alternative is Liquibase with the spring-boot-starter-liquibase starter: changes are described in a changelog, db/changelog/db.changelog-master.yaml by default; the format is YAML, JSON, XML or SQL.

sqlV1__create_product.sql
CREATE TABLE product (    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,    name VARCHAR(100) NOT NULL,    price NUMERIC(12, 2) NOT NULL,    created_at TIMESTAMP WITH TIME ZONE,    category_id BIGINT REFERENCES category (id));

Lazy loading and N+1

A @ManyToOne(fetch = FetchType.LAZY) association is read from the database only when you access it. If you loop over a hundred products and call getCategory().getName() on each, that is a hundred and one queries — the N+1 problem. Load the association in the same query with @EntityGraph on a repository method.

javaProductRepository.java
@EntityGraph(attributePaths = "category")List<Product> findByCategoryName(String name);

Spring Boot keeps the EntityManager open until the end of the web request by default (spring.jpa.open-in-view=true), and lazy associations keep being read in the background even in the controller. Turn the property off and load the data you need in the service — then the extra queries are immediately visible.

propertiesapplication.properties
spring.jpa.open-in-view=false

The SQL query language is covered in the SQL reference, the section “SELECT: selecting, filtering and sorting”; the way the database itself works, in the PostgreSQL reference.

Section sources

the section is written from these pages

Testing

A Spring Boot application is tested at three levels: a plain unit test without Spring for the logic, a slice (@WebMvcTest, @DataJpaTest) for a single layer, and @SpringBootTest for the application as a whole. The less context a test starts, the faster it runs.

The spring-boot-starter-test starter brings in JUnit, Spring Test and Spring Boot Test, AssertJ, Hamcrest, Mockito, JSONassert, JsonPath and Awaitility. The slices live in their own modules: @WebMvcTest in spring-boot-webmvc-test and @DataJpaTest in spring-boot-data-jpa-test; the test starters spring-boot-starter-webmvc-test and spring-boot-starter-data-jpa-test supply them.

LevelAnnotationWhat is started
Unit testnoneonly the class under test and mocks
Web slice@WebMvcTestSpring MVC: controllers, @ControllerAdvice, filters; no services or repositories
Data slice@DataJpaTestJPA, repositories, an embedded database; the transaction is rolled back after the test
The whole application@SpringBootTestthe entire context; with RANDOM_PORT — a real server on a random port

A unit test without Spring

A class with constructor injection is created with plain new: a Mockito mock stands in for the repository, and Clock.fixed for the clock. No Spring context is started, and the test runs in milliseconds.

javaProductServiceTests.java
class ProductServiceTests {     private final ProductRepository products =            mock(ProductRepository.class);    private final Clock clock = Clock.fixed(            Instant.parse("2026-11-01T10:00:00Z"), ZoneOffset.UTC);    private final ProductService service =            new ProductService(products, clock);     @Test    void createSavesProduct() {        when(products.save(any(Product.class)))                .thenAnswer(call -> call.getArgument(0));         var view = service.create(                new NewProduct("Tea", new BigDecimal("12000")));         assertThat(view.name()).isEqualTo("Tea");    }}

Web slice: @WebMvcTest

@WebMvcTest(ProductController.class) starts only Spring MVC for a single controller and configures MockMvc and MockMvcTester: requests go through without a real server. Regular @Component and @Service beans do not get into the slice, so the controller’s dependency is replaced with @MockitoBean.

javaProductControllerTests.java
@WebMvcTest(ProductController.class)class ProductControllerTests {     @Autowired    private MockMvcTester mvc;     @MockitoBean    private ProductService service;     @Test    void returnsProduct() {        given(service.get(1L)).willReturn(                new ProductView(1L, "Tea", new BigDecimal("12000")));         assertThat(mvc.get().uri("/api/products/1"))                .hasStatusOk()                .bodyJson()                .extractingPath("$.name").isEqualTo("Tea");    }     @Test    void rejectsEmptyName() {        assertThat(mvc.post().uri("/api/products")                .contentType(MediaType.APPLICATION_JSON)                .content("""                        {"name": "", "price": 100}                        """))                .hasStatus(HttpStatus.BAD_REQUEST);    }}

Data slice: @DataJpaTest

@DataJpaTest configures JPA, the Spring Data repositories and an embedded database, if one is among the dependencies — H2, for example. Each test runs inside a transaction and is rolled back at the end, and SQL queries are written to the log. TestEntityManager is a convenient way to prepare data.

javaProductRepositoryTests.java
@DataJpaTestclass ProductRepositoryTests {     @Autowired    private TestEntityManager entityManager;     @Autowired    private ProductRepository products;     @Test    void findsByNameIgnoringCase() {        entityManager.persist(new Product("Green tea",                new BigDecimal("12000"), Instant.now()));         var found = products.findByNameIgnoreCase("green TEA");         assertThat(found).isPresent();    }}

The whole application: @SpringBootTest

@SpringBootTest assembles the context exactly as when the application starts. By default no server is started (the MOCK environment); with webEnvironment = RANDOM_PORT a real server starts on a free port, and @AutoConfigureRestTestClient provides a client that talks to it.

javaShopApplicationTests.java
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)@AutoConfigureRestTestClientclass ShopApplicationTests {     @Autowired    private RestTestClient client;     @Test    void createsProduct() {        client.post().uri("/api/products")                .contentType(MediaType.APPLICATION_JSON)                .body("{\"name\": \"Tea\", \"price\": 12000}")                .exchange()                .expectStatus().isCreated();    }}

A real database: Testcontainers

To check your queries and migrations against the same DBMS as in production, run it in Docker through Testcontainers. @ServiceConnection passes the container’s address and password to Spring Boot, and they take precedence over the spring.datasource.* properties. You need the spring-boot-testcontainers and testcontainers-junit-jupiter modules, the Testcontainers module for your database and a working Docker.

javaPostgresTests.java
@Testcontainers@SpringBootTestclass PostgresTests {     @Container    @ServiceConnection    static PostgreSQLContainer postgres =            new PostgreSQLContainer("postgres:18");     @Autowired    private ProductRepository products;     @Test    void startsWithEmptyTable() {        assertThat(products.count()).isZero();    }}

Choosing checks and test data is covered in the “Test design” reference; this section is only about the Spring Boot tools.

Section sources

the section is written from these pages

Deployment and Actuator

In production, a Spring Boot application runs as an executable jar with an embedded server: directly via java -jar, as a systemd service, or in a container. Actuator is plugged in alongside: the /actuator/health endpoint and metrics are needed by monitoring and Kubernetes checks.

The executable jar

./mvnw package builds a jar into target/ containing your code and all the libraries; with Gradle it is ./gradlew bootJar, and the result lands in build/libs/. JVM options are written before -jar, Spring Boot settings — after the file name.

bashon the server
./mvnw packagejava -Xmx512m -jar target/shop-0.0.1-SNAPSHOT.jar \  --spring.profiles.active=prod

A container image without a Dockerfile

The Spring Boot plugin builds an OCI image through Cloud Native Buildpacks — no Dockerfile is needed, only access to the Docker daemon. An application in such an image does not run as root. The default image name is docker.io/library/ plus the project name and version; a custom one is set by the spring-boot.build-image.imageName property.

bashon the build machine
./mvnw spring-boot:build-image \  -Dspring-boot.build-image.imageName=registry.example.com/shop:1.0

Your own Dockerfile with layers

If the image is built with a Dockerfile, split the jar into layers: libraries change less often than the code, so Docker takes their layers from the cache. The tools mode extracts the layers with the extract --layers command; the final image runs a small application.jar that references the extracted libraries.

dockerfileDockerfile
FROM bellsoft/liberica-openjre-debian:25-cds AS builderWORKDIR /builderCOPY target/*.jar application.jarRUN java -Djarmode=tools -jar application.jar \    extract --layers --destination extracted FROM bellsoft/liberica-openjre-debian:25-cdsWORKDIR /application# libraries live in separate layers and change less often than the codeCOPY --from=builder /builder/extracted/dependencies/ ./COPY --from=builder /builder/extracted/spring-boot-loader/ ./COPY --from=builder /builder/extracted/snapshot-dependencies/ ./COPY --from=builder /builder/extracted/application/ ./ENTRYPOINT ["java", "-jar", "application.jar"]

Dockerfile instructions and image building in general — in the Docker reference, section “Dockerfile and its instructions”.

The systemd service

On a server without containers, the jar is run as a systemd service. In the unit, specify a dedicated user, the full path to java, and SuccessExitStatus=143: with this code the JVM exits on SIGTERM, and systemd must not treat a graceful stop as a failure. How to write and enable unit files — in the systemd reference, section “Services: .service units”.

ini/etc/systemd/system/shop.service
[Unit]Description=shopAfter=network.target [Service]User=shopGroup=shopType=execExecStart=/usr/bin/java -jar /opt/shop/shop.jarWorkingDirectory=/opt/shopSuccessExitStatus=143 [Install]WantedBy=multi-user.target

Graceful shutdown

On the stop signal, Spring Boot stops accepting new requests and lets the current ones finish — this is enabled by default for Tomcat, Jetty and Reactor Netty. The wait time is set by spring.lifecycle.timeout-per-shutdown-phase (30 seconds by default), and server.shutdown=immediate switches the mechanism off.

propertiesapplication.properties
spring.lifecycle.timeout-per-shutdown-phase=20s

Actuator: endpoints

The spring-boot-starter-actuator starter adds endpoints for observing the application, each available at /actuator/<id>. Over HTTP only health is open by default; the rest are enabled with a list in management.endpoints.web.exposure.include. If Spring Security is on the classpath and there is no SecurityFilterChain of your own, all endpoints except health require sign-in.

propertiesapplication.properties
management.endpoints.web.exposure.include=health,info,prometheusmanagement.endpoint.health.show-details=when-authorized
EndpointWhat it shows
healthapplication status; details — via show-details
infoinformation about the application; build and git repository by default
metricsthe metrics the application has collected
prometheusmetrics in Prometheus format; needs the micrometer-registry-prometheus dependency
loggerslog levels; lets you change them on the fly
mappingsall @RequestMapping paths
env, configpropsenvironment properties and @ConfigurationProperties; values are masked as ******
heapdump, threaddumpheap and thread dumps of the JVM
shutdownshuts the application down; disabled by default

Kubernetes checks

Actuator publishes the health groups /actuator/health/liveness (is the application alive) and /actuator/health/readiness (is it ready to take traffic). If the Actuator endpoints are moved to a separate port, enable management.endpoint.health.probes.add-additional-paths=true: the groups become available as /livez and /readyz on the main port. Do not add checks of external systems to liveness: if the database fails, Kubernetes will restart every instance at once. Manifests and the checks themselves — in the Kubernetes reference, section “Workloads: Deployment, StatefulSet, Job”.

textexample output
$ curl http://localhost:8080/actuator/health{"groups":["liveness","readiness"],"status":"UP"}

Section sources

the section is written from these pages

Security

Spring Security protects an application with a filter chain that checks every request before it reaches the controller: who sent it (authentication) and what they are allowed to do (authorisation). As soon as the starter is added, every address is locked down, and you define your own rules in a SecurityFilterChain bean.

What the starter changes

With spring-boot-starter-security, every address, including /error, requires sign-in. Spring Boot creates a user with a random password and prints the password to the log at startup. The browser gets a sign-in form and an API client gets HTTP Basic — the method is chosen by the Accept header.

textexample output
Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35 This generated password is for development use only. ...

This password is for development only. Change the name and password with the spring.security.user.name and spring.security.user.password properties; for production you declare your own rules and users.

The filters run in a strict order: CSRF protection, then authentication, then authorisation. AuthorizationFilter comes last, and ExceptionTranslationFilter just before it turns a denial into a response: not signed in — 401 and a prompt for credentials; no permission — 403.

The chain looks like this with httpBasic; other sign-in methods add their own authentication filters.

Access rules

Declare a SecurityFilterChain bean and Spring Boot auto-configuration steps aside: from then on only your rules apply, including those for Actuator. The rules are checked top-down until the first match, so specific paths go above general ones, and anyRequest() comes last.

javaSecurityConfig.java
@Configurationpublic class SecurityConfig {     @Bean    public SecurityFilterChain securityFilterChain(HttpSecurity http)            throws Exception {        http            .authorizeHttpRequests((auth) -> auth                // rules are checked top-down                .requestMatchers(EndpointRequest.to("health")).permitAll()                .requestMatchers(HttpMethod.GET, "/api/products/**")                    .permitAll()                .requestMatchers("/api/admin/**").hasRole("ADMIN")                .anyRequest().authenticated())            .httpBasic(withDefaults());        return http.build();    }     @Bean    public PasswordEncoder passwordEncoder() {        return PasswordEncoderFactories.createDelegatingPasswordEncoder();    }}
RuleWho is allowed in
permitAll()everyone, no sign-in needed
authenticated()any signed-in user
hasRole("ADMIN")a user with the ROLE_ADMIN role: the ROLE_ prefix is added automatically
hasAuthority("read")a user with the read authority
denyAll()nobody

Put anyRequest().authenticated() or denyAll() last: then a new address that nobody added to the rules will not turn out to be open.

javadon’t do this
@Beanpublic WebSecurityCustomizer ignoreCss() {    return (web) -> web.ignoring().requestMatchers("/css/**");}
javathe right way
http.authorizeHttpRequests((auth) -> auth        .requestMatchers("/css/**").permitAll()        .anyRequest().authenticated());

Requests matched by ignoring() bypass the filters entirely, and Spring Security will not add the security headers to them. permitAll() also lets everyone in, but the headers stay in place.

Passwords

Passwords are stored only as a hash. PasswordEncoderFactories.createDelegatingPasswordEncoder() returns a DelegatingPasswordEncoder: it hashes with bcrypt and writes the algorithm at the start of the string — {bcrypt}$2a$10$.... Later you can switch to another algorithm, and the old passwords will keep verifying.

java
String hash = encoder.encode(rawPassword);boolean ok = encoder.matches(rawPassword, hash);

CSRF

Protection against CSRF (cross-site request forgery) is on by default for the unsafe methods — POST, PUT, DELETE: such a request without a CSRF token gets a 403. It is needed when the browser signs in through a session cookie. A service that only non-browser clients call — for example mobile apps with a token in a header — may switch it off:

javaSecurityConfig.java
http.csrf((csrf) -> csrf.disable());

In a browser single-page application (SPA) you do not switch the protection off; instead you enable the csrf((csrf) -> csrf.spa()) mode designed for JavaScript clients.

Actuator and OAuth2

Until you declare your own SecurityFilterChain, Spring Boot also protects the Actuator endpoints with sign-in. With your own chain these rules are yours to write: EndpointRequest builds matchers for the Actuator addresses, taking their base path into account. For an API with JWT tokens, add the OAuth2 resource server (the spring-security-oauth2-resource-server module); how OAuth 2.0 and JWT work is covered in the OAuth and OIDC reference, sections “Flows: authorization code, PKCE and others” and “JWT, JWS and JWKS”.

Section sources

the section is written from these pages

Common errors and diagnostics

If the application does not start, look for the APPLICATION FAILED TO START block at the end of the log: the failure analyzer names the cause (Description) and what to do (Action). If the cause is not there, run the application with --debug and read the auto-configuration conditions report.

Order of checks

  1. Find the APPLICATION FAILED TO START block and read Description and Action.
  2. If the block is not there, look in the stack trace for the lowest Caused by: — that is the original cause.
  3. Compare java -version with java.version in pom.xml: the JDK version must not be older than the one the code was compiled for.
  4. Run with --debug and read the auto-configuration conditions report: which auto-configurations matched, which did not, and why.
bashon the host
java -jar target/shop-0.0.1-SNAPSHOT.jar --debug

Port 8080 was already in use

Cause: the port is already taken by another process. Often it is a second instance of the same application — for example, one left running from the IDE.

textexample output
***************************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.
bashwhat is listening on the port
sudo ss -ltnp 'sport = :8080'
bashon the host
# another port; 0 — any free portjava -jar target/shop-0.0.1-SNAPSHOT.jar --server.port=8081

The constructor is missing a bean

Cause: the class that should become a bean lies outside the main class’s package or is not annotated with @Service, @Component or @Repository. The second common case — the starter that creates the needed bean automatically is missing, for example spring-boot-starter-data-jpa for repositories.

text
com/example/shop/ShopApplication.java        @SpringBootApplicationcom/example/shop/product/ProductService.java will be foundcom/example/billing/InvoiceService.java      will not be found
  • Move the class into the main class’s package or below it: com.example.shop.billing.
  • Add the @Service or @Component annotation, or declare the bean with an @Bean method.
  • Check that the starter for the technology is present in pom.xml.

Failed to configure a DataSource

Cause: spring-boot-starter-data-jpa is among the dependencies, but spring.datasource.url is not set, and there is no embedded database (H2, HSQL) among the dependencies — Spring Boot does not know what to connect to.

propertiesapplication.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/shopspring.datasource.username=shop

The database driver, for example org.postgresql:postgresql, must also be among the dependencies. If no database is needed yet, remove the data starter.

The spring.datasource.* properties have no effect

Cause: the application declares its own DataSource bean. The pool auto-configuration then steps aside, and nobody reads the spring.datasource.* properties.

bashin the project directory
grep -rn "DataSource" src/main/java

Remove your own bean and configure the pool with properties, or configure the declared DataSource fully in code.

Tables were created on H2 but not on PostgreSQL

Cause: JPA creates tables automatically only in an embedded database — H2, HSQL or Derby. For PostgreSQL and other external databases Spring Boot leaves the schema alone, and the first query fails with an error about a missing table.

  • Manage the schema with Flyway or Liquibase migrations — how to set that up is covered in the section “Data: Spring Data JPA”.
  • For quick experiments on your own machine you can enable spring.jpa.hibernate.ddl-auto=update, but not for a production database.

Whitelabel Error Page

Cause: no handler matches the request — a typo in the path, or the controller answers at another address. Spring Boot directs all errors to the built-in /error endpoint: an API client receives JSON with the status and the description of the error, a browser receives the default Whitelabel Error Page, and an unknown route gets 404 Not Found.

bashcheck
curl -i http://localhost:8080/api/unknown
  • Check the path in the @RequestMapping or @GetMapping annotation against the address of the request.
  • Return your own API errors in the Problem Details format — the section “Web and REST controllers” covers how to set that up.
  • The default page is replaced with your own: for that, add a view named error.

java.lang.UnsupportedClassVersionError

Cause: the classes were compiled for a newer version of Java than the one running them. The JVM reads the version number in the class file and refuses to load it.

bashin the project directory
java -versiongrep java.version pom.xml
  • Run with the same JDK as the build, or a newer one: java.version 25 needs JDK 25.
  • In the Dockerfile take a base image with the same version of Java as on the build machine.

The application starts and exits immediately

Cause: neither Spring MVC nor Spring WebFlux is among the dependencies, so Spring Boot builds an ordinary, non-web context: the server does not come up, and after main has run the program has nothing left to do. Add the spring-boot-starter-webmvc starter.

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Spring Boot 4.1. The latest release is 4.1.2 of 22 October 2026. A new minor version comes out twice a year, in May and November; a branch receives free support for at least a year, after which only commercial support remains.

BranchStatusLatest releaseSupported until
4.1covered by this reference4.1.2, 22 October 202631 July 2027
4.0supported4.0.9, 22 October 202631 December 2026
3.5free support has ended3.5.16, 25 June 202630 June 2026; commercial support until 30 June 2032

Java: this reference uses JDK 25 — for most vendors this is a long-term support release (LTS). JDK 25 was released on 16 September 2025, and the latest update is 25.0.5 of 20 October 2026. Spring Boot 4.1 requires Java 17 or later and works up to Java 27. The long-term support branches are 17, 21 and 25; JDK 27 is a short-term release.

What’s new in 4.1

  • Web: gRPC support — Spring gRPC servers and clients, including gRPC over HTTP/2 in a servlet container.
  • Web: HTTP clients accept InetAddressFilter, which blocks requests to specified addresses — protection against SSRF.
  • Configuration: spring.config.import accepts a file encoding — classpath:import.properties[encoding=utf-8]; the default is still ISO-8859-1.
  • Configuration: common Jackson read and write settings are set through the spring.jackson.read.* and spring.jackson.write.* properties.
  • Data: spring.datasource.connection-fetch=lazy takes a connection from the pool only when the first SQL query is needed.
  • Deployment and Actuator: the info endpoint reports uptime, time zone and the working directory of the process; the observability context is passed to @Async methods.
  • Security: in an OAuth2 resource server, authorities from a JWT can be extracted with SpEL expressions — the spring.security.oauth2.resourceserver.jwt.authorities-claim-expressions property.
  • Testing: Spock support is back.

Deprecated and removed

  • Everything deprecated in Spring Boot 4.0 has been removed in 4.1: clear the deprecation warnings before upgrading.
  • The layertools jar mode has been removed and replaced by tools: java -Djarmode=tools -jar app.jar.
  • Support for the embedded Apache Derby database is deprecated: the Derby project has been retired, move to H2 or HSQL.
  • -DskipTests no longer disables AOT processing of tests in the Maven plugin — use maven.test.skip.
  • LiveReload in DevTools is deprecated and will not be replaced.
  • The properties and classes for the Dynatrace V1 API are deprecated in favour of V2.

Security updates

The table lists Spring Boot, Spring Framework and Spring Security vulnerabilities from the official spring.io advisories of the last 12 months.

IdentifierWhat is affectedFixed in
CVE-2026-59270Spring Security: the embedded LDAP server (spring.ldap.embedded.*) listens on all interfaces and accepts a known administrator accountSpring Security 7.1.1, 7.0.7
CVE-2026-41707Spring Security: replay of a DPoP proofSpring Security 7.1.1, 7.0.7
CVE-2026-47841Spring Security: WebAuthn user verification bypass with distributed sessionsSpring Security 7.1.1, 7.0.7
CVE-2026-41842Spring Framework: denial of service when serving versioned static resourcesSpring Framework 7.0.8, 6.2.19
CVE-2026-41845Spring Framework: XSS via JavaScriptUtils.javaScriptEscape()Spring Framework 7.0.8, 6.2.19
CVE-2026-41850Spring Framework: denial of service when evaluating SpEL from user inputSpring Framework 7.0.8, 6.2.19
CVE-2026-40976Spring Boot: the default protection does not apply when an Actuator is present without spring-boot-healthSpring Boot 4.0.6
CVE-2026-40973Spring Boot: predictable temporary directory when server.servlet.session.persistent=trueSpring Boot 4.0.6, 3.5.14
CVE-2026-22732Spring Security: configured HTTP response headers may fail to be writtenSpring Security 7.0.4, 6.5.9
CVE-2026-22731Spring Boot: authentication bypass under an additional health group pathSpring Boot 4.0.4, 3.5.12

How to upgrade

  1. Upgrade to the latest release of your branch and clear the deprecation warnings: in the next minor version the deprecated code is already removed.
  2. Read the upgrade section for your branch in the release notes: for 4.0 → 4.1 it is “Upgrading from Spring Boot 4.0”, for 3.5 → 4.0 it is “Upgrading from Spring Boot 3.5” in the 4.0 release notes, with a separate migration guide attached to it.
  3. Change the version of spring-boot-starter-parent or the Gradle plugin to the latest 4.1.x and rebuild the project.
  4. Run the tests and check the application on a test environment.

Upgrade one minor version at a time: 3.5 → 4.0 → 4.1.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Java and Spring” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61