Sub topic 2
Setting up a Spring Boot web project
This chapter builds the project that the rest of the tutorial uses. It assumes you know Java 17 or later, have used Maven or Gradle, and understand dependency injection (a framework supplies an object's collaborators instead of the object creating them). It also assumes you have a JDK 17+ installed.
By the end you will have a runnable application with an embedded web server, a known package layout, and a smoke test that proves the setup works.
What a web project needs
A Spring Boot web application needs three things:
- A starter dependency. A starter is a single dependency that pulls in a curated set of libraries with compatible versions.
- A main class annotated with
@SpringBootApplication. - A build plugin that packages the application as an executable JAR.
The starter for REST work is spring-boot-starter-web. It brings in Spring MVC (the web framework), Jackson (JSON conversion), and an embedded Tomcat server. You do not install Tomcat or deploy a WAR file. The server starts inside your own JVM process.
| Dependency | What it adds | Used in this tutorial for |
|---|---|---|
| `spring-boot-starter-web` | Spring MVC, Jackson, embedded Tomcat | Controllers and JSON |
| `spring-boot-starter-validation` | Bean Validation (Hibernate Validator) | Validating request DTOs |
| `spring-boot-starter-test` | JUnit, Mockito, AssertJ, MockMvc support | Controller tests |
DTO stands for data transfer object, a plain class or record that carries data across a boundary such as an HTTP request. Later chapters use DTOs in detail.
Generating the project
The usual way to start is Spring Initializr at start.spring.io. Choose these settings:
- Project: Maven (Gradle works the same way).
- Language: Java.
- Spring Boot: the latest stable 3.x release.
- Group:
com.example, Artifact:bookshelf. - Packaging: Jar. Java: 17 or later.
- Dependencies: Spring Web, Validation.
Download the ZIP and unpack it. You can get the same result from a terminal:
curl https://start.spring.io/starter.zip \
-d type=maven-project \
-d language=java \
-d javaVersion=17 \
-d groupId=com.example \
-d artifactId=bookshelf \
-d packageName=com.example.bookshelf \
-d dependencies=web,validation \
-o bookshelf.zip
unzip bookshelf.zip -d bookshelfThe build file
The generated pom.xml looks like this. The version number is an example. Use whatever Initializr gives you.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.1</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>bookshelf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>Three details matter here:
- The parent POM manages versions. The starters have no
<version>element becausespring-boot-starter-parentpins a tested set of versions. Adding a version to a starter usually causes mismatches. spring-boot-maven-pluginbuilds the executable JAR and provides thespring-boot:rungoal.- The
validationstarter is separate. Since Spring Boot 2.3,spring-boot-starter-webno longer includes Bean Validation. Without this starter,@Validand constraint annotations such as@NotBlankwill not compile, or they compile but are silently ignored.
If you use Gradle, the equivalent dependencies block is:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}The main class and package layout
Initializr generates the entry point:
package com.example.bookshelf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BookshelfApplication {
public static void main(String[] args) {
SpringApplication.run(BookshelfApplication.class, args);
}
}@SpringBootApplication combines three annotations:
@SpringBootConfiguration, which marks the class as a source of bean definitions.@EnableAutoConfiguration, which configures beans based on the libraries on the classpath. Because Spring MVC and Tomcat are present, Boot creates a web server and aDispatcherServlet, the front controller that receives every request and routes it to a controller method.@ComponentScan, which finds@RestController,@Serviceand other stereotype classes.
The component scan starts at the package of the main class and covers its sub-packages only. A layout that works with this rule looks like this:
src/main/java/com/example/bookshelf/
├── BookshelfApplication.java
├── book/
│ ├── BookController.java
│ ├── BookService.java
│ ├── CreateBookRequest.java
│ └── BookResponse.java
└── error/
└── ApiExceptionHandler.java
src/main/resources/
└── application.properties
src/test/java/com/example/bookshelf/
└── book/
└── BookControllerTest.javaThis tutorial groups classes by feature (book) rather than by layer (controllers, services). Either layout works, as long as everything sits below com.example.bookshelf.
How startup works
The diagram shows what happens between main and the first request.
Configuration
Boot reads src/main/resources/application.properties at startup. The file can be empty, because every setting has a default. These are the ones you are most likely to change:
server.port=8080
spring.application.name=bookshelf
spring.mvc.problemdetails.enabled=true
spring.jackson.default-property-inclusion=non_nullserver.portchanges the listening port. Useserver.port=0to pick a random free port, which is useful in tests.spring.mvc.problemdetails.enabledturns on RFC 9457 error bodies for Spring MVC's own exceptions. The error-handling chapter covers it.spring.jackson.default-property-inclusion=non_nullomits null fields from JSON output.
Spring Boot also accepts YAML (application.yml). Pick one format per project. If both files exist, .properties takes precedence for keys defined in both.
You can override any property from outside the JAR, without rebuilding. An environment variable named SERVER_PORT overrides server.port, and a command-line argument such as --server.port=9090 overrides both.
A smoke test endpoint
Before you build real features, confirm the setup with a tiny controller. Create src/main/java/com/example/bookshelf/PingController.java:
package com.example.bookshelf;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PingController {
@GetMapping("/ping")
public Map<String, String> ping() {
return Map.of("status", "ok");
}
}Start the application and call it:
./mvnw spring-boot:runIn a second terminal:
curl -i http://localhost:8080/pingExpected output, with a few headers omitted:
HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
{"status":"ok"}The Content-Type header shows that Jackson converted the Map to JSON without any extra configuration. If you generated the project without the Maven wrapper, use mvn spring-boot:run instead. You can delete PingController once the real controller from the next chapter exists.
To run the packaged form, which is how you deploy it:
./mvnw package
java -jar target/bookshelf-0.0.1-SNAPSHOT.jarDeveloper conveniences
spring-boot-devtools is an optional dependency that restarts the application when compiled classes change. Add it with <scope>runtime</scope> and <optional>true</optional>. It is excluded from the packaged JAR by default. It is a convenience only, and nothing in this tutorial depends on it.
The default startup log is also useful for diagnosis. The lines to look for are Tomcat started on port 8080 and Started BookshelfApplication in ... seconds. If either is missing, the application did not finish starting.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Port 8080 was already in use` | Another process holds the port | Stop it or set `server.port` |
| Application starts and exits immediately | `spring-boot-starter-web` is missing, so Boot starts no web server | Add the starter and reload the build |
| Every URL returns 404 | Controller is outside the scanned package | Move it below the main class's package |
| `release version 17 not supported` | The JDK running Maven is older than `java.version` | Install JDK 17+ and check `JAVA_VERSION` or `JAVA_HOME` |
| `@Valid` has no effect | Validation starter missing | Add `spring-boot-starter-validation` |
| `NoSuchMethodError` at startup | Starter versions were overridden and no longer match | Remove explicit versions and let the parent manage them |
Choosing between starter-web and WebFlux
Spring Boot also offers spring-boot-starter-webflux, a reactive stack that runs on Netty. This tutorial uses spring-boot-starter-web (servlet stack, one thread per request), which is simpler to write, debug and test. If both starters are on the classpath, Boot chooses Spring MVC. Do not add WebFlux to an MVC project unless you need its WebClient.
Exercise
You add a class OrderController annotated with @RestController and @GetMapping("/orders") in the package com.example.orders. Your main class is com.example.bookshelf.BookshelfApplication. The application starts without errors, but GET /orders returns 404. What is the cause, and what are two ways to fix it?
Show answer
The component scan starts at com.example.bookshelf, and com.example.orders is not a sub-package of it, so the controller is never registered as a bean. Fix it by moving the class into a package below com.example.bookshelf (for example com.example.bookshelf.orders), or by widening the scan, for example @SpringBootApplication(scanBasePackages = "com.example"). Moving the class is the better option because it keeps the default behavior.
Exercise
Which property and value would you use to make the application listen on a random free port, and which two other ways can override server.port without editing application.properties?
Show answer
Set server.port=0. You can override server.port with the environment variable SERVER_PORT or with the command-line argument --server.port=9090.