Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 66 ยท Practice and Review

Common Mistakes and Debugging Startup Failures

Read and fix common Spring Boot failures: NoSuchBean, circular dependencies, port in use, 404 versus 405, LazyInitializationException, self-invocation and debug mode.

Every Spring Boot developer meets the same wall of red text sooner or later. A stack trace of two hundred lines, a banner that says APPLICATION FAILED TO START, a 404 for an endpoint that is clearly in the code. The good news is that Boot's errors are usually very precise, and the same dozen problems cause most of them. Once you know how to read the message and which problems are most common, most failures take minutes to fix instead of hours.

This lesson teaches a method first (where in the output to look) and then walks through the failures you will actually see: missing and ambiguous beans, circular dependencies, a busy port, a missing DataSource, bad configuration values, 404 versus 405 responses, LazyInitializationException and transactions that silently do nothing. It ends with the debug flag, which shows what auto-configuration decided. Spring cannot run on this site, so real messages appear in read-only blocks, and three live stand-ins show why each kind of failure happens: a circular-dependency detector, a request router that returns 404 and 405 for different reasons, and a proxy that skips a transactional self-call. For the practice side, see Practice Exercises with Solutions.

A method for reading failures

Bottom first The last Caused by is the real reason.
Description + Action Boot often tells you the fix.
One change Fix one thing, rerun, read again.
--debug Ask Boot what it decided.
1 / 2

Read the failure report from the bottom

When the context cannot start, Boot catches the exception and prints a failure report instead of a raw stack trace, if a failure analyzer recognises the problem. It has two parts you should read in order: Description says what went wrong, Action says what Boot suggests.

TEXT
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.example.shop.OrderService required a bean of type 'com.example.shop.PaymentGateway' that could not be found.

Action:

Consider defining a bean of type 'com.example.shop.PaymentGateway' in your configuration.

When there is no analyzer for the problem, you get a long stack trace instead. Read it from the bottom: Spring wraps exceptions in exceptions (BeanCreationException inside UnsatisfiedDependencyException inside ApplicationContextException), and the line that starts with the last Caused by: names the real cause. The top lines only tell you which bean was being created at the time. Copy that last line, not the first, into your notes or search.

NoSuchBeanDefinitionException: nothing to inject

The report above means the container looked for a bean of type PaymentGateway and found none. Walk through the usual reasons:

  1. The class is not a bean. It lacks @Component, @Service, @Repository or a @Bean method (see Component Scanning and Stereotypes).
  2. It is outside the scanned packages. Component scanning starts at the package of the @SpringBootApplication class. A class in com.other is invisible to an application in com.example.shop.
  3. A condition switched it off. An @ConditionalOnProperty, @Profile or @ConditionalOnClass was false in this environment (see Conditional Beans).
  4. The starter or dependency is missing. For example no spring-boot-starter-data-jpa means no EntityManager or repositories.

The opposite error is NoUniqueBeanDefinitionException: expected single matching bean but found 2. Two beans fit the type and Spring will not guess. Mark one @Primary, name the one you want with @Qualifier, or inject a List if you need them all (see Qualifiers, @Primary and Collections).

Circular dependencies

OrderService needs PaymentService and PaymentService needs OrderService. With constructor injection neither can be created first, and since Spring Boot 2.6 the application refuses to start:

TEXT
The dependencies of some of the beans in the application context form a cycle:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”
|  orderService defined in file [.../OrderService.class]
โ†‘     โ†“
|  paymentService defined in file [.../PaymentService.class]
โ””โ”€โ”€โ”€โ”€โ”€โ”˜

Action:

Relying upon circular references is discouraged and they are prohibited by default.
Update your application to remove the dependency cycle between beans.

The setting spring.main.allow-circular-references=true makes the error go away, and it is almost always the wrong fix: it hides a design problem. A cycle means two classes know too much about each other. Break it by moving the shared behaviour into a third class that both use, by turning one direction into an event (see Application Events and Runners), or, as a last resort, by injecting an ObjectProvider<OrderService> and asking for it only when needed.

The stand-in below finds a cycle in a graph of "bean needs bean" edges by depth-first search and prints it in the same shape as Boot's report. It also reports a missing dependency, which is how the container discovers NoSuchBean. It is a model of the idea, not Spring's implementation.

Java Finding a dependency cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Edit the third graph to remove one edge and rerun: the cycle disappears. In a real project the cleanest edge to cut is usually the one that was added "just to call one method".

Port in use, and the DataSource that was not configured

Two more failures have analyzers and are fixed by reading the Action part.

TEXT
Web server failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

Usually an older instance of your own application is still running. Stop it, or choose another port with server.port=8081 (or --server.port=0 in tests, which picks a free port). On Windows, netstat -ano | findstr :8080 shows the process id; on Linux and macOS use lsof -i :8080.

TEXT
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

You added a JDBC-capable starter (data-jpa or jdbc) but gave Boot no database. Either set spring.datasource.url, username and password, add an embedded database such as H2 for tests, or, if the app should not use a database at all, remove the starter. A related error is Schema-validation: missing table [orders] when ddl-auto=validate finds that your migrations and entities disagree (see Database Migrations with Flyway).

Configuration that does not bind

TEXT
Binding to target ... MailProperties failed:

    Property: app.mail.from
    Value: "null"
    Origin: "app.mail.from" from property source "systemProperties"
    Reason: must not be blank

This is Type-Safe @ConfigurationProperties doing its job: a required value is missing or invalid, and the report names the property, the value and where it came from. The usual causes are a typo in the key (app.mail.form), YAML indentation that nests a key under the wrong parent, a profile file that is not active, or an environment variable with the wrong name (APP_MAIL_FROM maps to app.mail.from). Check what Boot actually sees with the env actuator endpoint or the startup log line The following 1 profile is active.

404 versus 405 (and 400, 415)

A request that "does not work" can fail in several different layers, and the status code tells you which one:

Status Meaning Typical cause
404 No handler for this path Wrong URL, wrong context path, controller not scanned, missing / or typo in the mapping
405 The path exists, but not for this HTTP method POST sent to a @GetMapping, a response with an Allow header
415 The body's Content-Type is not accepted Sending form data or a missing header to an endpoint that consumes JSON
400 The request could not be understood Malformed JSON, a wrong type in a path variable, a failed @Valid check
401 / 403 Security stopped it Not logged in, or not allowed (see Spring Security Fundamentals)

The difference between 404 and 405 matters: 405 proves your path is right and only the method is wrong. The router stand-in applies those rules to a list of routes. Notice that 405 is only chosen when some route matches the path with another method, and that the Allow header lists those methods.

Java Why 404 and why 405

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

GET /book returns 404 because the path is misspelled, while PUT /books/42 returns 405 because that path exists for GET and DELETE. In a real application, also check the server.servlet.context-path, a missing @RestController, and, in Boot 3.2 and later, the message No static resource ..., which is the 404 that appears when no controller mapping matched and Boot fell back to looking for a file.

LazyInitializationException

TEXT
org.hibernate.LazyInitializationException: Cannot lazily initialize collection of role
'com.example.shop.Author.books' with key '7': no session

A @OneToMany collection is loaded lazily: Hibernate puts a placeholder in the entity and fetches the rows when you first touch it, which needs an open session. If you return the entity from a service and the controller or JSON serializer touches author.getBooks() after the transaction ended, there is no session left and Hibernate throws.

Fix it by loading what you need while the transaction is open: a join fetch query or an @EntityGraph (see Entity Relationships and the N+1 Problem), or, better, map to a DTO inside the service method so the web layer never sees entities. Do not make the relationship EAGER globally: it loads data you do not need everywhere else. And be aware that Boot's spring.jpa.open-in-view defaults to true, which keeps the session open during the whole web request. That hides the exception in controllers while quietly holding a database connection during view rendering and serialization. Setting it to false makes the problem appear early, in development, which is where you want it.

The annotation that does nothing: self-invocation

@Transactional, @Cacheable, @Async and method security all work through a proxy: Spring wraps your bean in an object that does the extra work and then calls your code. A call from another bean goes through the proxy. A call from a method to another method of the same object uses this, which is the raw object, so the annotation is silently ignored. The same happens with private or final methods, and with objects you create using new. There is no error and no log line; the transaction just does not exist.

The stand-in builds a real JDK dynamic proxy that begins and ends a "transaction" around methods annotated @Transactional. Watch which calls print BEGIN.

Java The proxy that self-calls skip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Case 2 prints no BEGIN at all. In real code you fix it by moving the method to another bean (the usual and cleanest answer), by using TransactionTemplate for programmatic control, or, rarely, by injecting the bean into itself as case 3 does. More on proxies and propagation in Transactions with @Transactional.

Ask Boot what it decided: the debug flag

When behaviour is surprising (a bean you expected is missing, one you did not expect exists), turn on the conditions evaluation report. Start the application with --debug (or set debug=true):

Terminal
java -jar shop.jar --debug

Boot prints a report listing every auto-configuration as positive matches (applied, with the conditions that passed), negative matches (skipped, with the condition that failed, such as @ConditionalOnClass did not find required class 'com.zaxxer.hikari.HikariDataSource'), exclusions and unconditional classes. The same information is available from a running application at /actuator/conditions and the list of beans at /actuator/beans (see Actuator: Health, Metrics and Info). Background on how these decisions are made is in How Auto-Configuration Works.

A few other switches help during diagnosis:

  • logging.level.org.springframework.web=DEBUG shows how requests are mapped and which handler ran.
  • logging.level.org.hibernate.SQL=DEBUG prints each SQL statement, which is the fastest way to spot N+1 queries.
  • spring.main.lazy-initialization=true speeds up startup but delays wiring errors until a bean is first used. Do not leave it on while hunting a startup failure.

A short checklist for the next failure

  1. Find the last Caused by: line, or the Description and Action of the report.
  2. Classify it: wiring, configuration, web mapping, data or proxy.
  3. Check the simple causes first: package of the main class, missing annotation, typo in a property, wrong profile.
  4. Reproduce with the smallest change that triggers it, and fix one thing at a time.
  5. Add a test that would have caught it (a @WebMvcTest, or a context-load test with @SpringBootTest).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A long stack trace is full of nested BeanCreationExceptions. Where is the real cause?

    Spring wraps the original exception several times. The deepest cause, listed last, names the actual problem.
  2. 2. A request to PUT /books/42 returns 405 while GET /books/42 works. What does that tell you?

    405 means a route matched the path but not the method; the Allow header lists the methods that do work. A wrong path would be 404.
  3. 3. Why does @Transactional on archive() have no effect when archiveAll() in the same class calls this.archive()?

    Transactions are applied by a proxy around the bean. A call on this never passes through it.
  4. 4. What does spring.main.allow-circular-references=true do?

    It lets the container resolve some cycles with partially built beans. The classes still depend on each other, so refactor instead.
  5. 5. Which tool shows why an auto-configuration was or was not applied?

    Debug mode prints positive and negative matches with the failing condition. The same data is at /actuator/conditions.

Summary

  • Read failure reports as Description then Action; in raw stack traces, the last Caused by: is the real reason.
  • Missing beans come from a missing stereotype, a package outside the scan, a false condition or a missing starter; ambiguous beans need @Primary or @Qualifier.
  • Circular dependencies are a design smell; break the cycle instead of enabling allow-circular-references.
  • 404 means no path matched, 405 means the path matched but not the method, 415 means the wrong content type, 400 a bad body.
  • LazyInitializationException means you touched a lazy association after the session closed; fetch what you need inside the transaction or return DTOs.
  • Proxy-based annotations are skipped by self-invocation; use --debug and /actuator/conditions when auto-configuration surprises you.

Next: Spring Boot Interview Questions.