Spring Boot Tutorial
Spring Boot is a layer on top of the Spring Framework that turns a few lines of code into a running, production-ready application. It picks sensible defaults, configures beans automatically based on the libraries you add, and starts an embedded Tomcat server, so there is no WAR to build and no server to install. This Spring Boot tutorial builds a CourseHub REST service from an empty folder to an executable JAR.
The examples use Spring Boot 4.1.2 (Spring Framework 7) with Java 25. Spring Boot 4 needs Java 17 or newer.
What Spring Boot Adds to Spring
| Feature | What it does for you |
|---|---|
| Starters | One dependency per feature (spring-boot-starter-webmvc) brings every library it needs, in compatible versions |
| Auto-configuration | Creates beans such as the DispatcherServlet, JSON converter and DataSource when the right classes are on the classpath |
| Embedded server | Tomcat runs inside your application; java -jar starts everything |
| Externalized configuration | application.properties, environment variables and command-line arguments set values without code changes |
| Profiles | Separate settings for dev, test and prod |
| Actuator | Ready-made health, info and metrics endpoints |
How it works:
- Everything from Spring Framework Basics still applies: beans, constructor injection,
@Component,@Valueand profiles. Spring Boot simply creates theApplicationContextand much of the configuration for you. - In the Java Web Application lesson you wrote a WAR and deployed it to a separate Tomcat. With Spring Boot, Tomcat is a library inside your JAR.
Create a Project With Spring Initializr
Open start.spring.io, choose Maven, Java, Spring Boot 4.1.2 and Java 25, set the group to com.gocourse and artifact to coursehub, and add the Spring Web and Spring Boot Actuator dependencies. The same project can be downloaded from the command line:
curl https://start.spring.io/starter.zip \
-d type=maven-project -d language=java \
-d bootVersion=4.1.2 -d javaVersion=25 \
-d groupId=com.gocourse -d artifactId=coursehub -d name=CourseHub \
-d packageName=com.gocourse.coursehub \
-d dependencies=web,actuator \
-o coursehub.zip
unzip coursehub.zip -d coursehub && cd coursehub
coursehub/
├── mvnw, mvnw.cmd Maven wrapper (no Maven install needed)
├── pom.xml
└── src/
├── main/
│ ├── java/com/gocourse/coursehub/CourseHubApplication.java
│ └── resources/
│ ├── application.properties
│ ├── static/ CSS, JS, images served as-is
│ └── templates/ server-side HTML templates
└── test/java/com/gocourse/coursehub/CourseHubApplicationTests.java
How it works:
- The Maven wrapper (
./mvnw) downloads the right Maven version on first use, so every developer builds the same way. static/files are served directly at the site root.templates/is used by template engines such as Thymeleaf in the Spring MVC lesson.
The pom.xml: Parent, Starters and Plugin
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
<relativePath/>
</parent>
<groupId>com.gocourse</groupId>
<artifactId>coursehub</artifactId>
<version>0.0.1-SNAPSHOT</version>
<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-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
How it works:
- The parent POM manages versions of hundreds of libraries, which is why the starters have no
<version>. Upgrading Spring Boot upgrades all of them together. spring-boot-starter-webmvcbrings Spring MVC, embedded Tomcat and Jackson for JSON. In Spring Boot 3 this starter was calledspring-boot-starter-web.spring-boot-maven-pluginadds thespring-boot:rungoal and repackages the build into an executable JAR.
The Main Class and @SpringBootApplication
package com.gocourse.coursehub;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CourseHubApplication {
public static void main(String[] args) {
SpringApplication.run(CourseHubApplication.class, args);
}
}
./mvnw spring-boot:run
Output (shortened):
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v4.1.2)
INFO Starting CourseHubApplication using Java 25 with PID 41872
INFO No active profile set, falling back to 1 default profile: "default"
INFO Tomcat initialized with port 8080 (http)
INFO Tomcat started on port 8080 (http) with context path '/'
INFO Started CourseHubApplication in 1.6 seconds (process running for 1.9)
@SpringBootApplication combines | Purpose |
|---|---|
@SpringBootConfiguration | Marks the class as a @Configuration source |
@EnableAutoConfiguration | Turns on auto-configuration |
@ComponentScan | Scans com.gocourse.coursehub and all sub-packages |
How it works:
SpringApplication.runcreates the application context, runs auto-configuration, starts Tomcat and keeps the JVM alive until you press Ctrl+C.- Keep the main class in the root package. Classes outside
com.gocourse.coursehubare not scanned and silently ignored.
Build Your First REST Endpoint
package com.gocourse.coursehub;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(@RequestParam(defaultValue = "student") String name) {
return "Hello, " + name + "! Welcome to CourseHub.";
}
}
curl http://localhost:8080/hello
curl "http://localhost:8080/hello?name=Asha"
Output:
Hello, student! Welcome to CourseHub.
Hello, Asha! Welcome to CourseHub.
How it works:
@RestControlleris a@Component, so component scanning finds it. Its return values are written straight into the response body.@GetMapping("/hello")maps HTTPGET /helloto the method, and@RequestParamreads?name=with a default when it is missing.- Compare this with a servlet: no
doGet, nogetWriter(), no URL mapping inweb.xml. Spring MVC'sDispatcherServlet, created by auto-configuration, does the routing.
Return JSON From a Service and Controller
Records returned from a controller become JSON automatically.
package com.gocourse.coursehub.course;
public record Course(String code, String title, int feeInr) {}
package com.gocourse.coursehub.course;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
@Service
public class CourseService {
private final Map<String, Course> courses = new ConcurrentHashMap<>();
public CourseService() {
save(new Course("java", "Java Programming", 4999));
save(new Course("go", "Go Language", 2999));
}
public List<Course> findAll() {
return courses.values().stream().sorted(Comparator.comparing(Course::code)).toList();
}
public Optional<Course> findByCode(String code) {
return Optional.ofNullable(courses.get(code));
}
public Course save(Course course) {
courses.put(course.code(), course);
return course;
}
}
package com.gocourse.coursehub.course;
import java.net.URI;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@RestController
@RequestMapping("/api/courses")
public class CourseController {
private final CourseService courseService;
public CourseController(CourseService courseService) {
this.courseService = courseService;
}
@GetMapping
public List<Course> all() {
return courseService.findAll();
}
@GetMapping("/{code}")
public Course one(@PathVariable String code) {
return courseService.findByCode(code)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No course " + code));
}
@PostMapping
public ResponseEntity<Course> create(@RequestBody Course course) {
Course saved = courseService.save(course);
return ResponseEntity.created(URI.create("/api/courses/" + saved.code())).body(saved);
}
}
curl http://localhost:8080/api/courses
curl -i -X POST http://localhost:8080/api/courses \
-H "Content-Type: application/json" \
-d '{"code":"docker","title":"Docker Essentials","feeInr":1999}'
curl -i http://localhost:8080/api/courses/rust
Output:
[{"code":"go","title":"Go Language","feeInr":2999},{"code":"java","title":"Java Programming","feeInr":4999}]
HTTP/1.1 201
Location: /api/courses/docker
Content-Type: application/json
{"code":"docker","title":"Docker Essentials","feeInr":1999}
HTTP/1.1 404
Content-Type: application/json
{"timestamp":"2026-11-18T05:42:10.512Z","status":404,"error":"Not Found","path":"/api/courses/rust"}
How it works:
- Spring injects
CourseServiceinto the controller's constructor exactly as in plain Spring. - Jackson, added by the web starter, turns the
List<Course>into a JSON array and turns the request body into aCourserecord for@RequestBody. ResponseEntity.created(...)sets status201and theLocationheader.ResponseStatusExceptionproduces Spring Boot's standard JSON error with the right status code. The design rules behind these status codes are covered in REST API in Java.
Configure the App With application.properties
# src/main/resources/application.properties
spring.application.name=coursehub
server.port=8080
# Our own settings
coursehub.platform-name=GOCOURSE
coursehub.max-courses-per-student=3
coursehub.support-email=support@gocourse.example
package com.gocourse.coursehub;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "coursehub")
public record CourseHubProperties(String platformName, int maxCoursesPerStudent, String supportEmail) {}
package com.gocourse.coursehub;
import com.gocourse.coursehub.course.CourseService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@ConfigurationPropertiesScan // finds @ConfigurationProperties records
public class CourseHubApplication {
public static void main(String[] args) {
SpringApplication.run(CourseHubApplication.class, args);
}
@Bean
CommandLineRunner startupReport(CourseHubProperties props, CourseService courseService) {
return args -> System.out.printf("%s ready: %d courses, max %d per student, help: %s%n",
props.platformName(), courseService.findAll().size(),
props.maxCoursesPerStudent(), props.supportEmail());
}
}
Output (at the end of startup):
INFO Started CourseHubApplication in 1.7 seconds (process running for 2.0)
GOCOURSE ready: 2 courses, max 3 per student, help: support@gocourse.example
How it works:
@ConfigurationProperties(prefix = "coursehub")binds everycoursehub.*key to the record. Relaxed binding mapsmax-courses-per-studenttomaxCoursesPerStudentand converts the text toint.- Grouping settings in one typed record is safer than many
@Valuestrings: one place to look, and a typo in a type fails at startup. - A
CommandLineRunnerbean runs once after the application has fully started. Use it for startup checks, data loading or reports.
Override Settings With Profiles and Command-Line Arguments
# src/main/resources/application-dev.properties
server.port=8081
coursehub.platform-name=GOCOURSE (DEV)
coursehub.max-courses-per-student=10
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
Output (shortened):
INFO The following 1 profile is active: "dev"
INFO Tomcat started on port 8081 (http) with context path '/'
GOCOURSE (DEV) ready: 2 courses, max 10 per student, help: support@gocourse.example
| Source (higher wins) | Example |
|---|---|
| Command-line argument | --server.port=9090 |
| Environment variable | SERVER_PORT=9090, COURSEHUB_PLATFORMNAME=Demo |
application-{profile}.properties | application-dev.properties |
application.properties | default values |
How it works:
application.propertiesalways loads first. An active profile's file then overrides only the keys it contains, sosupport-emailkeeps its default value.- Environment variables use uppercase with underscores. This is how containers and cloud platforms set database passwords and ports without touching the JAR.
How Spring Boot Auto-Configuration Works
Auto-configuration classes are ordinary @Configuration classes with conditions. Each one asks questions such as "Is this class on the classpath?" and "Has the developer already defined this bean?".
| Condition annotation | Applies the configuration when |
|---|---|
@ConditionalOnClass | A class is on the classpath (for example DispatcherServlet) |
@ConditionalOnMissingBean | You have not defined a bean of that type yourself |
@ConditionalOnProperty | A property has a given value |
@ConditionalOnWebApplication | The app is a web application |
./mvnw spring-boot:run -Dspring-boot.run.arguments=--debug
Output (small part of the report):
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches:
-----------------
DispatcherServletAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'
...
Negative matches:
-----------------
...
How it works:
- Because the web starter put
DispatcherServleton the classpath, Spring MVC was configured. No database starter was added, so noDataSourcebean exists. - Positive matches list every auto-configuration that was applied and why; negative matches list the ones skipped and the condition that failed. Read this report whenever a bean you expected is missing.
- Most auto-configured beans use
@ConditionalOnMissingBean. If you declare your own bean of the same type, Spring Boot backs off and uses yours. That is how you customize anything Boot sets up.
Monitor the App With Spring Boot Actuator
# add to application.properties
management.endpoints.web.exposure.include=health,info
management.info.env.enabled=true
info.app.name=CourseHub
info.app.version=1.0
curl http://localhost:8080/actuator/health
curl http://localhost:8080/actuator/info
Output:
{"status":"UP"}
{"app":{"name":"CourseHub","version":"1.0"}}
How it works:
/actuator/healthreturnsUPwhile the app and its dependencies (database, disk space) are healthy. Load balancers and Kubernetes call it to decide whether to send traffic.- Only endpoints listed in
exposure.includeare reachable over HTTP. Keep sensitive ones such asenvandbeanshidden in production.
Package and Run an Executable JAR
./mvnw clean package
java -jar target/coursehub-0.0.1-SNAPSHOT.jar --server.port=9090
Output (shortened):
[INFO] Building jar: /home/asha/coursehub/target/coursehub-0.0.1-SNAPSHOT.jar
[INFO] BUILD SUCCESS
...
INFO Tomcat started on port 9090 (http) with context path '/'
GOCOURSE ready: 2 courses, max 3 per student, help: support@gocourse.example
How it works:
packageruns the tests, then the Boot plugin repackages the JAR so it contains your classes, every dependency JAR and a launcher.- The same file runs on any machine with Java 25: a laptop, a VM or a Docker image.
--server.port=9090overrides the property for this run only.
Real-World Example: Spring Boot Tutorial Project With an Enrollment Rule
CourseHub must stop a student from joining more courses than the limit in coursehub.max-courses-per-student. The rule lives in a service, the limit in configuration, and the controller answers with clear HTTP status codes.
# add to application.properties so error JSON includes the reason
server.error.include-message=always
package com.gocourse.coursehub.enrollment;
import com.gocourse.coursehub.CourseHubProperties;
import com.gocourse.coursehub.course.CourseService;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
@Service
public class EnrollmentService {
public record EnrollmentResult(String student, String courseCode, int coursesTaken, int limit) {}
private final CourseService courseService;
private final CourseHubProperties props;
private final Map<String, Set<String>> coursesByStudent = new ConcurrentHashMap<>();
public EnrollmentService(CourseService courseService, CourseHubProperties props) {
this.courseService = courseService;
this.props = props;
}
public EnrollmentResult enroll(String student, String courseCode) {
courseService.findByCode(courseCode).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "Course " + courseCode + " does not exist"));
Set<String> taken = coursesByStudent.computeIfAbsent(student, key -> ConcurrentHashMap.newKeySet());
synchronized (taken) { // one student's enrollments change one at a time
if (taken.contains(courseCode)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, student + " is already enrolled in " + courseCode);
}
if (taken.size() >= props.maxCoursesPerStudent()) {
throw new ResponseStatusException(HttpStatus.CONFLICT,
student + " already has " + taken.size() + " courses (limit " + props.maxCoursesPerStudent() + ")");
}
taken.add(courseCode);
return new EnrollmentResult(student, courseCode, taken.size(), props.maxCoursesPerStudent());
}
}
}
package com.gocourse.coursehub.enrollment;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EnrollmentController {
public record EnrollmentRequest(String student, String courseCode) {}
private final EnrollmentService enrollmentService;
public EnrollmentController(EnrollmentService enrollmentService) {
this.enrollmentService = enrollmentService;
}
@PostMapping("/api/enrollments")
@ResponseStatus(HttpStatus.CREATED)
public EnrollmentService.EnrollmentResult enroll(@RequestBody EnrollmentRequest request) {
return enrollmentService.enroll(request.student(), request.courseCode());
}
}
# Add two more courses, then send five enrollment requests for Asha and one for Ravi
for course in docker python; do
curl -s -X POST localhost:8080/api/courses -H "Content-Type: application/json" \
-d "{\"code\":\"$course\",\"title\":\"$course course\",\"feeInr\":1999}" > /dev/null
done
for course in java go docker java python; do
curl -s -X POST localhost:8080/api/enrollments -H "Content-Type: application/json" \
-d "{\"student\":\"asha\",\"courseCode\":\"$course\"}"; echo
done
curl -s -X POST localhost:8080/api/enrollments -H "Content-Type: application/json" \
-d '{"student":"ravi","courseCode":"kotlin"}'; echo
Output:
{"student":"asha","courseCode":"java","coursesTaken":1,"limit":3}
{"student":"asha","courseCode":"go","coursesTaken":2,"limit":3}
{"student":"asha","courseCode":"docker","coursesTaken":3,"limit":3}
{"timestamp":"2026-11-18T05:51:03.218Z","status":409,"error":"Conflict","message":"asha is already enrolled in java","path":"/api/enrollments"}
{"timestamp":"2026-11-18T05:51:03.231Z","status":409,"error":"Conflict","message":"asha already has 3 courses (limit 3)","path":"/api/enrollments"}
{"timestamp":"2026-11-18T05:51:03.240Z","status":404,"error":"Not Found","message":"Course kotlin does not exist","path":"/api/enrollments"}
How it works:
- Layers. The controller only converts HTTP to method calls. The business rule sits in
EnrollmentService, which could be reused by a scheduled job or a message listener. - Configuration-driven rule. The limit comes from
CourseHubProperties. Starting with thedevprofile raises it to 10 with no code change, and the fifth request would then succeed. - Thread safety. Tomcat handles requests on many threads.
ConcurrentHashMapkeeps the map safe, and locking one student's set prevents two parallel requests from both passing the limit check. - Meaningful status codes. Success returns
201 Created, a duplicate or over-limit request returns409 Conflict, and an unknown course returns404. Withinclude-message=alwaysthe JSON explains why; leave it off for public APIs if messages could reveal internal details. - Where this goes next. The in-memory maps disappear on restart. The Spring Data JPA lesson replaces them with a real database, and the Spring MVC lesson adds HTML pages to the same kind of application.