Most of “fixing a bug” is finding the real cause, not changing code; this post groups common Spring Boot errors by symptom, with how to read the logs and how to fix them. Four of the errors here are real ones hit while running the lab on Spring Boot 4.0.3 and JDK 21 (mvn test: 29 tests, 28 passed, 1 skipped because this machine couldn’t run Docker). Afterwards you have a diagnosis routine instead of guessing or pasting logs into an AI.
At a glance:
flowchart TD
S[Symptom] --> Q{Kind of error?}
Q -->|stack trace| ST["Last Caused by + your line"]
Q -->|won't start| AF["Read APPLICATION FAILED TO START"]
Q -->|LazyInitializationException| LZ["Fetch in service, return DTO"]
Q -->|401| A1["Token missing/bad/expired"]
Q -->|403| A3[Known but not allowed]
A3 -.->|"trap: Exception.class handler"| E5["403 becomes 500"]
K["Stop: SIGTERM first, kill -9 last"]
1. Reading logs and stack traces
Key idea: the real exception is usually wrapped several times; the root cause sits in the last Caused by, and the place to fix is usually the first line in your own package.
Three steps for any long stack trace:
- Scroll to the last
Caused by: that’s the root error. The layers above are the framework wrapping it. - In that section, find the first line with your package (for example
dev.lab.hr). That’s where your code calls into the failure. - Read the whole message, including the bracketed parts (table name, constraint name, entity id).
When the app can’t start, Spring Boot prints a dedicated block (built by a FailureAnalyzer) with Description: and Action:. A real one from running two copies of the lab on the same port:
***************************
APPLICATION FAILED TO START
***************************
Description:
Web server failed to start. Port 18081 was already in use.
2. Startup failures
Key idea: the three most common startup failures are a port conflict, a missing bean and DataSource configuration; all three have clear messages in the APPLICATION FAILED TO START block.
Port conflict (“Port 8080 was already in use”): another process (often an old copy of your own app) holds the port.
# macOS / Linux
lsof -i :8080 # see the PID and process name
kill <PID> # SIGTERM: let the app shut down gracefully
kill -9 <PID> # only if it refuses to stop
# Windows
netstat -ano | findstr :8080
taskkill /PID <PID> /F
To run several copies side by side (or in tests), use server.port=0 to pick a random free port.
Missing bean (“Parameter 0 of constructor in X required a bean of type ‘Y’ that could not be found”). Three usual causes:
- Class
Ysits outside the package of the@SpringBootApplicationclass, so the component scan can’t see it. Move it into a sub-package. - A missing annotation (
@Service,@Repository), or the bean is switched off by@Profile/@ConditionalOn.... Yis an interface and no implementation is a bean.
Circular dependency (“The dependencies of some of the beans in the application context form a cycle”): A needs B, B needs A. Since Spring Boot 2.6 cycles are forbidden by default. Don’t turn spring.main.allow-circular-references back on; move the shared part into a third bean or use an event. More in IoC and Dependency Injection.
“Failed to configure a DataSource: ‘url’ attribute is not specified”: the JPA starter is present but spring.datasource.url isn’t set and there’s no embedded DB, or the active profile’s file lacks it. Check the profiles printed in the startup log.
3. ClassNotFound, NoSuchMethodError and stale builds
Key idea: “class/method doesn’t exist” at runtime almost always means a stale build, or two versions of one library on the classpath.
ClassNotFoundExceptionafter renaming a package:target/classesstill holds the old classes and the IDE hasn’t recompiled. Run./mvnw clean compile; in VS Code use “Java: Clean Java Language Server Workspace”; in IntelliJ reload the Maven project.NoSuchMethodError/NoClassDefFoundErrorat runtime even though it compiles: the code was compiled against version A of a library but version B is loaded at runtime. Look at the dependency tree:
./mvnw dependency:tree -Dincludes=com.fasterxml.jackson.core
Fix it by removing hand-written versions so Spring Boot’s BOM manages them, or by <exclusion> of the stray version another library pulls in.
4. Common JPA errors
Key idea: JPA errors are hard because they surface away from their cause: a proxy touched after the session closed, or SQL running earlier or later than you think.
4.1. LazyInitializationException (a real lab bug)
The refresh-token test returned 500. The log:
org.hibernate.LazyInitializationException: Could not initialize proxy [dev.lab.hr.user.User#3] - no session
at dev.lab.hr.user.User$HibernateProxy.getRoles(Unknown Source)
Cause: the @Transactional service method rotate() returned a User entity (a lazy proxy). The controller called user.getRoles() after the transaction had closed. The lab sets spring.jpa.open-in-view=false, so there was no session left to load data.
The fix: load everything you need inside the transaction and return plain data (a record), not the entity:
public record Rotated(String email, List<String> roles, String rawToken) {}
@Transactional(noRollbackFor = InvalidRefreshTokenException.class)
public Rotated rotate(String rawToken) {
// ... check the token, revoke the old one ...
User user = current.getUser();
String next = issueInFamily(user, current.getFamilyId());
var roles = user.getRoles().stream().map(r -> r.getName()).sorted().toList(); // still inside the transaction
return new Rotated(user.getEmail(), roles, next);
}
4.2. A unique violation thrown earlier than expected (a real lab bug)
The test expected the unique-constraint violation at flush(), but the exception came from save() itself. The reason: the entity uses GenerationType.IDENTITY, so the DB generates the id on INSERT. To hand back an entity with its id, Hibernate must run the INSERT immediately in save(); it can’t wait until flush.
// IDENTITY: save() already ran the INSERT, so the assertion must wrap the save call itself
assertThatThrownBy(() -> permissions.saveAndFlush(new Permission("A2", "/api/v1/a", "GET", "X")))
.isInstanceOf(DataIntegrityViolationException.class);
The practical consequence: with IDENTITY, Hibernate can’t batch INSERTs. For bulk inserts consider SEQUENCE (PostgreSQL) with a large allocationSize.
Two more JPA/JSON errors: JSON recursion and data.sql before tables
Infinite JSON recursion (StackOverflowError or HttpMessageNotWritableException: Infinite recursion): the controller returns an entity with a bidirectional relation, User.company points to Company.users which points back to User. Jackson loops forever. It often comes with LazyInitializationException or leaks sensitive fields like the password.
The proper fix: don’t return entities from the API; return DTO records with only the needed fields (the lab’s UserResponse has no password and lists role names). @JsonIgnore or @JsonManagedReference are band-aids that still expose your DB structure as the API contract.
data.sql says “Table not found”: Spring Boot runs SQL scripts before Hibernate creates tables through ddl-auto. Set spring.jpa.defer-datasource-initialization=true so the script runs afterwards. With non-embedded DBs (MySQL, PostgreSQL), scripts only run with spring.sql.init.mode=always. In production use Flyway instead of either (see auto-configuration and the lifecycle).
5. Security errors: 401, 403, and a 403 that became a 500
Key idea: in a JWT API, 401 means authentication failed (token missing, bad signature, expired) and 403 means you’re known but not allowed. Read the headers and the security log before changing code.
| Symptom | Meaning | What to check |
|---|---|---|
401 with WWW-Authenticate: Bearer error="invalid_token" |
broken, badly signed, expired token, or wrong issuer | exp, iss, whether both sides use the same secret/key, the algorithm |
401 with just WWW-Authenticate: Bearer |
no token sent | does Authorization: Bearer ... reach the server (proxy, CORS) |
| 403 | authenticated, missing permission | do the actual authorities have ROLE_, which claim becomes authorities |
| 403 on POST although logged in | CSRF still on | a chain for a Bearer-header API disables CSRF for /api/** |
The first two 401 rows describe the resource server’s default entry point; a custom entry point (like the lab’s) only writes Bearer, so then you rely on the log.
Turn on detailed logging to see which filter refused and what authorities were present:
logging.level.org.springframework.security=TRACE
The most common 403: the token carries "roles": ["ADMIN"], but the default converter reads the scope claim and adds a SCOPE_ prefix, so hasRole('ADMIN') (meaning ROLE_ADMIN) never matches. How to change the converter is in RBAC and OAuth2 authorization; the token’s own traps are in authentication and JWT.
CORS: Postman works, the browser says “blocked by CORS policy”. The browser sends an OPTIONS request (preflight) first; if security blocks the preflight (401) or the Access-Control-Allow-Origin header is missing, the real request is never sent. Configure CORS inside Spring Security with http.cors(...) and explicit origins, never * with cookies. The full explanation is in Web and HTTP.
6. Use the debugger instead of println
Key idea: a breakpoint shows the real state at the exact moment of failure; the three skills worth learning are conditional breakpoints, evaluate expression and remote debugging.
- Line breakpoint: run the app in Debug mode in the IDE, stop at the suspect line, inspect variables, step through (step over, step into).
- Conditional breakpoint: stop only when
id == 42oremail.contains("test"). No more pressing Continue a hundred times in a loop. - Exception breakpoint: stop as soon as
LazyInitializationExceptionis thrown, even if the framework catches it later. - Evaluate expression: while paused, run an expression (
user.getRoles().size(),auth.getAuthorities()) to test a hypothesis without editing code. - Remote debug: attach the IDE to an app running outside it (a container, another dev machine):
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar app.jar
Then create a “Remote JVM Debug” configuration pointing at port 5005. Never open this port where real data lives: anyone who can connect can run arbitrary code.
A diagnosis routine for when you don’t know where to start
- Reproduce: write a test (or a
curlcommand) that fails every time. You can’t fix what you can’t reproduce. All four lab bugs were caught by tests, not by clicking around. - Narrow down the layer: the status code and log tell you where. A 401/403 before the controller is the filter chain; a 400 is binding/validation; a 500 with a JPA stack trace is the data layer.
- One hypothesis, one change: change one thing, rerun the test. Change three things at once and you won’t know which one worked.
- Confirm by breaking it: as the lab did with the
AccessDeniedExceptionhandler: remove the fix, see the test go red again, and only then be sure it was the cause. - Keep the test so the bug can’t come back (a regression test).
When asking an AI for help, give it exactly three things: the relevant code, the full error message (including Caused by), and what you expected versus what happened. A hundred lines of log without code only gets you a guess.
Remember
- Read a stack trace from the last
Caused byand find the line that belongs to your code. - Know three causes of “required a bean that could not be found”.
- Explain why
LazyInitializationExceptionhappens and fix it without enabling open-in-view. - Tell 401 from 403 in a JWT API, and know why
@PreAuthorizecan return 500. - Use conditional breakpoints, exception breakpoints and remote debugging.
Interview questions
Junior
The app says “Port 8080 was already in use”. What do you do?
Find the process holding the port (lsof -i :8080 or netstat -ano), stop it with SIGTERM, or change server.port.
It’s usually an old copy of the same app still running in the IDE. Use kill -9 only if the process won’t stop, because it skips graceful shutdown.
What’s the difference between 401 and 403?
401: the server can’t tell who you are (token missing, invalid or expired). 403: it knows who you are, but you lack permission.
On 401 the client should log in again or refresh the token. On 403 logging in again doesn’t help; you need to be granted access.
Mid
What is LazyInitializationException and how do you fix it?
It’s thrown when a lazy relation (a proxy) is touched after the Hibernate session closed; fix it by loading what you need inside the transaction and returning a DTO.
Use JOIN FETCH, @EntityGraph, or map to a DTO right in the service. Enabling open-in-view hides the error but holds a connection for the whole request and hides N+1.
The app won’t start: “required a bean of type X that could not be found”. What could cause it?
Class X is outside the scanned packages, it lacks a stereotype annotation, or the bean is switched off by a profile or condition.
Check the package of the @SpringBootApplication class, the annotation on X, the active profiles, and the condition report (--debug) if X should come from an auto-config.
An endpoint with @PreAuthorize returns 500 instead of 403. Why?
Because the AccessDeniedException thrown inside the controller call is caught by an @ExceptionHandler(Exception.class) in the @RestControllerAdvice, which returns 500.
Authorization failures in the filter chain never reach the advice; method security does. Add a dedicated handler for AccessDeniedException (re-throw it or return 403).
NoSuchMethodError at runtime although the code compiles. How do you investigate?
It’s a sign of two versions of one library: compiled against one, running with the other. Use mvn dependency:tree to find the extra one.
Fix it by letting the Spring Boot BOM manage versions, removing hand-written versions, or excluding the transitive dependency with the wrong version. Then clean to drop old classes.
Senior
A bug only happens on staging and you can’t reproduce it locally. How do you approach it?
Compare the environments first (profiles, environment variables, versions, data), gather evidence from logs and traces, then reproduce it in a test under staging-like conditions.
- Check actual properties via
/actuator/envand the profiles in the startup log. - Raise log levels for one package for a short time via
/actuator/loggers, without redeploying. - Use the trace id to join logs across services.
- Remote debug only where there’s no real data and access is controlled.
- Reproduce with Testcontainers on the same DB version as staging.
Useful phrases for interviews
- “I read the stack trace from the last Caused by, then look for the first frame in our own package.”
- “The root cause was a lazy proxy touched after the transaction had closed.”
- “First I wrote a test that reproduces the bug every time.”
- “NoSuchMethodError at runtime usually points to a dependency conflict, so I check the dependency tree.”
- “A 401 means we couldn’t authenticate the caller; a 403 means we did, but they lack the permission.”
- “The catch-all handler swallowed the AccessDeniedException, so method security returned a 500.”
- “The browser sends an OPTIONS preflight before the real request, and our security chain was rejecting it.”
- “I confirmed the fix by removing it and watching the regression test fail again.”
Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.