SteelReed

Search

Search posts, questions…

5. Spring Boot

Common Spring Boot errors and how to debug them: from port conflicts to a 403 that became a 500

A symptom-first troubleshooting guide: port in use, ClassNotFound and dependency conflicts, reading the APPLICATION FAILED TO START block, LazyInitializationException, 401 vs 403 in a JWT API, @PreAuthorize turned into 500, CORS, JSON recursion, IDENTITY saves failing early, data.sql running before tables exist, and using the debugger.

18 Nov 20268 min readMid

–

1. The problem

The refresh-token test returns 500. The log has 80 lines of stack trace, the first one in DispatcherServlet. You change three things at once, the test goes green, but you don't know which change mattered. A week later the bug is back.

2. Key idea

Most bug-fixing time goes into finding the real cause. Debug like a doctor: ask about symptoms (logs, status codes), narrow down the layer, run tests (a reproducing test, breakpoints), then prescribe.

Read a stack trace in three steps: scroll to the last Caused by (the layers above are just the framework wrapping it); find the first line in your own package; read the whole message, including the bracketed parts (table, constraint, entity id).

2.1 Which symptom, which cause?

Symptom Common cause Fix
"Port 8080 was already in use" an old instance is still running lsof -i :8080, kill <PID>; tests use server.port=0
"required a bean of type 'Y' that could not be found" Y outside the @SpringBootApplication package, missing @Service move it into a subpackage
"form a cycle" A needs B, B needs A extract a third bean or use an event
NoSuchMethodError, ClassNotFoundException stale build, two versions of a library ./mvnw clean, dependency:tree, let the BOM manage versions
LazyInitializationException ... no session lazy relation touched after the transaction closed load it in the service, return a DTO
Infinite recursion when returning JSON returning an entity with a bidirectional relation return a DTO, never an entity
401 missing token, bad signature, expired check WWW-Authenticate, exp, iss
403 authenticated, lacks permission do the actual authorities have ROLE_?

Turn on logging.level.org.springframework.security=TRACE to see which filter rejected the request. Spring Boot 4 renamed some starters (spring-boot-starter-web became spring-boot-starter-webmvc); mixing Boot 3 and 4 poms often causes NoSuchMethodError.

2.2 Should you turn on open-in-view?

Approach Use when Don't use when
spring.jpa.open-in-view=true simple server-rendered pages REST APIs: holds a connection for the whole request, hidden N+1
JOIN FETCH, @EntityGraph, DTOs REST APIs, the default choice returning a large relation tree: use a dedicated query

3. In Java

JAVA
// LazyInitializationException: the controller called user.getRoles() after rotate() closed the transaction.
public record Rotated(String email, List<String> roles, String rawToken) {}
 
@Transactional
public Rotated rotate(String rawToken) {
    User user = current.getUser();
    String next = issueInFamily(user, current.getFamilyId());
    var roles = user.getRoles().stream().map(Role::getName).sorted().toList(); // still in the transaction
    return new Rotated(user.getEmail(), roles, next);                         // return a record, not an entity
}
 
// @PreAuthorize throws AccessDeniedException inside the controller, so an Exception.class handler swallows it: 403 becomes 500.
@ExceptionHandler(AccessDeniedException.class)
void accessDenied(AccessDeniedException ex) { throw ex; }   // rethrow so Spring Security returns 403

GenerationType.IDENTITY runs the INSERT immediately on save() because the DB generates the id, so a unique violation is thrown at save(), not at flush().

The debugger and a diagnosis routine
Skill Use when
Conditional breakpoint stop only when id == 42
Exception breakpoint stop as soon as LazyInitializationException is thrown, even if the framework catches it
Evaluate expression try auth.getAuthorities() without editing code
Remote debug -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005; never open it where real data lives

Routine: (1) reproduce with a test or a curl command; (2) narrow the layer (401/403 before the controller is the filter chain, 400 is binding, 500 with a JPA stack is the data layer); (3) one hypothesis, one change; (4) break it again: remove the fix, see the test go red, then you know it's the cause; (5) keep the test as a regression. If it's happening in production right now, limit the damage first (rollback, flip a flag).

4. Working with AI

Delegate to AI: explaining an unfamiliar error message, writing a reproducing test, reading dependency:tree.

Give the AI exactly three things: the relevant code, the full error message (including Caused by), and what you expected versus what happened.

Check the fix AI proposes:

  • It doesn't turn on open-in-view or allow-circular-references to "make the error go away".
  • It doesn't add @JsonIgnore instead of returning a DTO.
  • It doesn't hard-code versions the BOM already manages.
  • There's a test that's red before the fix and green after.

5. Exercises

Exercise 1: Read the incident: a regular user deleting a user gets a 500

You added @PreAuthorize("hasRole('ADMIN')") to DELETE /users/{id}. A regular user gets 500 "Unexpected error", not 403. The project has a @RestControllerAdvice with @ExceptionHandler(Exception.class). Diagnose and prove it.

Solution to Exercise 1
  • @PreAuthorize throws AccessDeniedException inside the controller (unlike filter-chain errors, which happen before DispatcherServlet), so the Exception handler catches it and returns 500.
  • Fix: add an AccessDeniedException handler that rethrows (or returns a 403 ProblemDetail).
  • Proof: a MockMvc test with a regular user expecting 403. Remove the dedicated handler and the test goes red again (500): that's the cause.

Exercise 2: Review AI's fix for a 403

The token has "roles": ["ADMIN"] and hasRole('ADMIN') always gives 403. AI suggests switching everything to permitAll() "to test first". What do you do instead?

Solution to Exercise 2
  • Reject permitAll(): it hides the bug and easily slips into production.
  • Turn on org.springframework.security=TRACE and look at the actual authorities: the default JWT converter reads the scope claim with a SCOPE_ prefix, so there's never a ROLE_ADMIN.
  • Fix: configure a JwtAuthenticationConverter to read the roles claim with a ROLE_ prefix. Test: a token with roles: [ADMIN] reaches the admin endpoint, one without gets 403.

Summary

  • Stack traces: last Caused by, then the first line in your package.
  • Won't start: read Description and Action first.
  • Lazy errors: load inside the transaction, return DTOs; don't turn on open-in-view.
  • 401 is unauthenticated, 403 lacks permission; a catch-all handler can turn 403 into 500.
  • Reproduce with a test, one change at a time, break it again to confirm the cause.

Further reading: Error handling in Spring Boot.

Practice interview questions on this topic

All Spring Boot questions →All Behavioral questions →All JPA & Hibernate questions →

Loading comments…
Next on the roadmapORM and JPA: JPQL, native queries, @Transactional and locking