Spring Boot Exercises
Time to practise. Some exercises have a runnable starter in plain Java that models a Spring concept — edit it, press ▶ Run, and compare with the expected result in the task. Others ask you to write real Spring code, which you can try in a project generated from start.spring.io. Give each one a real attempt before opening the solution.
Tip: The output block under a starter shows what the unfinished code prints. The task text tells you what the finished program should print.
Exercise 1: Constructor injection
OrderService creates its own EmailSender, so tests would send real emails. Refactor it to receive a Notifier through its constructor, then pass a RecordingNotifier that stores messages in a list. The finished program prints sent: [order 42 confirmed -> ana@example.com].
import java.util.ArrayList;
import java.util.List;
interface Notifier { void send(String to, String text); }
class EmailSender implements Notifier {
public void send(String to, String text) { System.out.println("SMTP: sending real email to " + to); }
}
class RecordingNotifier implements Notifier {
final List<String> sent = new ArrayList<>();
public void send(String to, String text) { sent.add(text + " -> " + to); }
}
class OrderService {
private final Notifier notifier = new EmailSender(); // TODO: inject through the constructor
void confirm(long orderId, String email) { notifier.send(email, "order " + orderId + " confirmed"); }
}
class Main {
public static void main(String[] args) {
RecordingNotifier recorder = new RecordingNotifier();
OrderService service = new OrderService(); // TODO: pass the recorder
service.confirm(42, "ana@example.com");
System.out.println("sent: " + recorder.sent);
}
}SMTP: sending real email to ana@example.com
sent: []
Show solution
class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; }
void confirm(long orderId, String email) { notifier.send(email, "order " + orderId + " confirmed"); }
}
// in main:
OrderService service = new OrderService(recorder);In Spring you would annotate OrderService with @Service and EmailSender with @Component; the container passes the Notifier bean into the constructor, while tests pass the recorder by hand.
Exercise 2: A books controller
Write a @RestController for an in-memory list of Book(long id, String title, String author) records with:
GET /api/books→ all books (200)GET /api/books/{id}→ one book (200) or 404 with no bodyPOST /api/books→ add a book from the JSON body, respond 201 with aLocationheader
The finished API behaves like this:
curl -s localhost:8080/api/books/1
echo
curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/api/books/9
curl -s -i -X POST localhost:8080/api/books -H "Content-Type: application/json" \
-d '{"title":"Refactoring","author":"Martin Fowler"}' | grep -E "^(HTTP|Location)"{"id":1,"title":"Clean Code","author":"Robert C. Martin"}
404
HTTP/1.1 201
Location: http://localhost:8080/api/books/3
Show solution
public record Book(long id, String title, String author) {}
public record NewBook(@NotBlank String title, @NotBlank String author) {}
@RestController
@RequestMapping("/api/books")
class BookController {
private final Map<Long, Book> books = new ConcurrentHashMap<>();
private final AtomicLong ids = new AtomicLong();
BookController() {
add(new NewBook("Clean Code", "Robert C. Martin"));
add(new NewBook("Effective Java", "Joshua Bloch"));
}
private Book add(NewBook b) {
Book book = new Book(ids.incrementAndGet(), b.title(), b.author());
books.put(book.id(), book);
return book;
}
@GetMapping
Collection<Book> all() { return books.values(); }
@GetMapping("/{id}")
ResponseEntity<Book> one(@PathVariable long id) {
return ResponseEntity.of(Optional.ofNullable(books.get(id)));
}
@PostMapping
ResponseEntity<Book> create(@Valid @RequestBody NewBook body, UriComponentsBuilder uri) {
Book saved = add(body);
return ResponseEntity.created(uri.path("/api/books/{id}").buildAndExpand(saved.id()).toUri()).body(saved);
}
}ConcurrentHashMap and AtomicLong matter: the controller is a singleton used by many request threads at once.
Exercise 3: Validate a request
Implement validate so it returns every violation, in field order: username must be 3–20 characters of a-z, 0-9 or _; email must contain exactly one @ with text on both sides; age must be at least 16. The finished program prints:
[]
[username: must match "[a-z0-9_]{3,20}", email: must be a well-formed email address, age: must be greater than or equal to 16]import java.util.ArrayList;
import java.util.List;
record SignupRequest(String username, String email, int age) {}
class Main {
static List<String> validate(SignupRequest r) {
List<String> errors = new ArrayList<>();
// TODO: check username, email and age
return errors;
}
public static void main(String[] args) {
System.out.println(validate(new SignupRequest("mai_dev", "mai@example.com", 29)));
System.out.println(validate(new SignupRequest("M!", "mai.example.com", 12)));
}
}[]
[]
Show solution
static List<String> validate(SignupRequest r) {
List<String> errors = new ArrayList<>();
if (r.username() == null || !r.username().matches("[a-z0-9_]{3,20}"))
errors.add("username: must match \"[a-z0-9_]{3,20}\"");
if (r.email() == null || !r.email().matches("[^@]+@[^@]+"))
errors.add("email: must be a well-formed email address");
if (r.age() < 16)
errors.add("age: must be greater than or equal to 16");
return errors;
}With Bean Validation the same rules are annotations on the record: @Pattern(regexp = "[a-z0-9_]{3,20}") String username, @Email String email, @Min(16) int age, plus @Valid on the controller parameter.
Exercise 4: Map exceptions to status codes
Complete statusFor so it behaves like @ExceptionHandler lookup: walk up the exception's class hierarchy and use the first class found in HANDLERS; return 500 if none matches. The finished program prints 404, 409, 400, 500.
import java.util.Map;
class NotFoundException extends RuntimeException {}
class ConflictException extends RuntimeException {}
class Main {
static final Map<Class<?>, Integer> HANDLERS = Map.of(
NotFoundException.class, 404,
ConflictException.class, 409,
IllegalArgumentException.class, 400);
static int statusFor(Throwable ex) {
// TODO: search ex.getClass(), then its superclasses
return 500;
}
public static void main(String[] args) {
System.out.println(statusFor(new NotFoundException()));
System.out.println(statusFor(new ConflictException()));
System.out.println(statusFor(new NumberFormatException()));
System.out.println(statusFor(new IllegalStateException()));
}
}500
500
500
500
Show solution
static int statusFor(Throwable ex) {
for (Class<?> c = ex.getClass(); c != null; c = c.getSuperclass()) {
Integer status = HANDLERS.get(c);
if (status != null) return status;
}
return 500;
}NumberFormatException extends IllegalArgumentException, so it gets 400. IllegalStateException has no handler in its hierarchy and falls through to 500.
Exercise 5: Name the query methods
Write Spring Data method declarations in TaskRepository (entity Task with title, done, priority, dueDate, project.name) for:
- all tasks that are not done, most urgent due date first
- whether a task with a given title exists, ignoring case
- the number of done tasks of a given priority
- the 5 most recent tasks whose title contains a word
- all tasks of a project, by project name
Show solution
public interface TaskRepository extends JpaRepository<Task, Long> {
List<Task> findByDoneFalseOrderByDueDateAsc();
boolean existsByTitleIgnoreCase(String title);
long countByDoneTrueAndPriority(Priority priority);
List<Task> findTop5ByTitleContainingIgnoreCaseOrderByDueDateDesc(String word);
List<Task> findByProjectName(String projectName); // traverses project.name
}Property paths like ProjectName follow associations (project.name). If the name becomes ambiguous you can write findByProject_Name.
Exercise 6: Paginate a list
Implement page so it returns the items of a zero-based page, plus totalPages. The finished program prints:
page 0: [a, b, c] of 3 pages
page 2: [g] of 3 pages
page 5: [] of 3 pagesimport java.util.List;
class Main {
record Page(List<String> content, int totalPages) {}
static Page page(List<String> all, int number, int size) {
// TODO: compute the slice and the number of pages
return new Page(List.of(), 0);
}
public static void main(String[] args) {
List<String> items = List.of("a", "b", "c", "d", "e", "f", "g");
for (int n : new int[] {0, 2, 5}) {
Page p = page(items, n, 3);
System.out.println("page " + n + ": " + p.content() + " of " + p.totalPages() + " pages");
}
}
}page 0: [] of 0 pages
page 2: [] of 0 pages
page 5: [] of 0 pages
Show solution
static Page page(List<String> all, int number, int size) {
int from = Math.min(number * size, all.size());
int to = Math.min(from + size, all.size());
int totalPages = (all.size() + size - 1) / size; // integer ceiling
return new Page(all.subList(from, to), totalPages);
}Math.min keeps a page beyond the end from throwing; it simply returns an empty list, just like Spring Data.
Exercise 7: Commit or roll back
runInTransaction should copy the balances, run the work on the copy, and only replace the real balances if the work finishes without a RuntimeException. On failure print rollback: <message>. The finished program prints:
rollback: insufficient funds
{ana=50, ben=10}
{ana=30, ben=30}import java.util.Map;
import java.util.TreeMap;
import java.util.function.Consumer;
class Main {
static Map<String, Integer> balances = new TreeMap<>(Map.of("ana", 50, "ben", 10));
static void runInTransaction(Consumer<Map<String, Integer>> work) {
// TODO: work on a copy, commit only on success
work.accept(balances);
}
static void transfer(Map<String, Integer> b, String from, String to, int amount) {
b.put(from, b.get(from) - amount);
if (b.get(from) < 0) throw new IllegalStateException("insufficient funds");
b.put(to, b.get(to) + amount);
}
public static void main(String[] args) {
for (int amount : new int[] {80, 20}) {
try {
runInTransaction(b -> transfer(b, "ana", "ben", amount));
} catch (RuntimeException e) {
System.out.println("uncaught: " + e.getMessage());
}
System.out.println(balances);
}
}
}uncaught: insufficient funds
{ana=-30, ben=10}
uncaught: insufficient funds
{ana=-50, ben=10}
Show solution
static void runInTransaction(Consumer<Map<String, Integer>> work) {
Map<String, Integer> working = new TreeMap<>(balances);
try {
work.accept(working);
balances = working; // commit
} catch (RuntimeException e) {
System.out.println("rollback: " + e.getMessage()); // working copy is discarded
}
}The starter shows the bug a missing transaction causes: the failed transfer left ana at -30, which then made the second, perfectly valid transfer fail too. With @Transactional on a service method, Spring gives you the commit/rollback behaviour of the solution.
Exercise 8: Secure the API
Write a SecurityFilterChain bean for a stateless API where GET /api/books/** is public, every other /api/** request needs the EDITOR role, /actuator/health is public, and everything else requires authentication. Use HTTP Basic.
Show solution
@Configuration
class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health").permitAll()
.requestMatchers(HttpMethod.GET, "/api/books/**").permitAll()
.requestMatchers("/api/**").hasRole("EDITOR")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
}Order matters: the GET rule must come before the general /api/** rule, otherwise reading books would also require EDITOR.
Test yourself
Why should an in-memory store inside a singleton controller use ConcurrentHashMap?
- It is faster to type
- Many request threads use the same controller instance concurrently
- Spring requires it
- HashMap cannot store records
In Exercise 7, what did the starter's missing rollback cause?
- Nothing; the result was correct
- A partial update left a negative balance
- A compile error
- An infinite loop