Skip to content
javahacks.dev
Spring Framework

Fix BeanCreationException Error Creating Bean With Name

Read a BeanCreationException trace to its root cause and fix the usual culprits: constructors that throw, bad schemas and absent services.

6 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the Spring, Spring Boot, Gradle and Apache Maven logos.

This is the exception Spring wraps around almost everything that goes wrong while building a bean. The first line looks like this:

Text
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/jdbc/autoconfigure/...]: Failed to initialize dependency 'dataSource' ...

and the name changes with each failure. The name is where the container noticed; the reason is below. The phases in which a bean can fail are laid out in how the Spring container works. If you see "Unsatisfied dependency" in the same trace, start with [UnsatisfiedDependencyException](/library/unsatisfieddependencyexception-fix-spring).

Find the cause

Take the last Caused by, the one with no further cause beneath it. Paste its class and message into the table below to find the section that applies.

Innermost exceptionSection
Your own exception, NullPointerExceptionYour code threw
Connection refused, PSQLException, CommunicationsExceptionThe database
Schema-validation: missing tableSchema mismatch
Could not resolve placeholderA property
ClassNotFoundException, NoClassDefFoundErrorClasspath

Your code threw

A constructor, a @PostConstruct method or a @Bean method that throws any exception produces this wrapper:

java
@Component
class RateCache {

    private final Map<String, Rate> rates;

    RateCache(RateClient client) {
        this.rates = client.fetchAll();      // throws when the remote service is down
    }
}

Startup now depends on a remote service. Move slow or fallible work out of initialization: load lazily on first use, or run it after startup in an ApplicationRunner with error handling. A bean that cannot be created takes the whole application down, which is right for a missing database and wrong for an optional cache.

The database is not reachable

entityManagerFactory, dataSource and flywayInitializer fail with a wrapper when the connection fails. The innermost message tells you more than the wrapper: Connection refused points at the host, port or container; an authentication failure points at credentials. See connection refused on port 5432 and Failed to configure a DataSource.

Schema validation failed

With spring.jpa.hibernate.ddl-auto=validate, Hibernate checks the schema against your mappings at startup. A missing table or column fails the entityManagerFactory bean:

Text
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [orders]

Run the migration, or fix the table name in @Table. Validation failing at startup is the purpose of the setting.

A property or a class is missing

A Could not resolve placeholder root is covered in the placeholder post. A ClassNotFoundException or NoClassDefFoundError at the bottom means a dependency is absent or mismatched at runtime; the mechanics are in the classpath errors post.

The @Bean method returned the wrong thing

java
@Bean
PaymentGateway gateway(@Value("${gateway.url}") String url) {
    return url.isBlank() ? null : new StripeGateway(url);
}

Returning null from a @Bean method is allowed but injecting it later gives confusing errors. Throw a clear exception instead, or use @ConditionalOnProperty so the bean is not defined.

Read the chain from the bottom

The message begins with the bean that was being created, and the useful part is at the end. The wrapper is the same for every cause, so only the last Caused by distinguishes them. Three runs of the same application, each failing for a different reason, show the pattern.

Text
BeanCreationException: Error creating bean with name 'badBean': Invocation of init method failed
Caused by: java.lang.IllegalStateException: catalog.url is not configured

The first line names badBean and says the failure was in an init method. The cause is the application's own exception, and its message is a configuration problem. The fix is in the code or properties of badBean.

Text
BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource
  [org/springframework/boot/hibernate/autoconfigure/HibernateJpaConfiguration.class]: Unable to build Hibernate SessionFactory
Caused by: jakarta.persistence.PersistenceException: Unable to build Hibernate SessionFactory
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [account]

The bean here is Spring Boot's own entityManagerFactory, and the application's code is not on the failing path. The deepest cause is the one to read: spring.jpa.hibernate.ddl-auto=validate found an Account entity with no table. The bean name pointed at infrastructure, and the real subject was the schema.

The lesson of both is to skip the name and read the last line. A bean name that belongs to Spring or a library nearly always means a configuration or environment problem, and a bean name from your own package nearly always means your code or one of its dependencies threw.

Dependencies that fail further down

Constructor injection creates a chain: creating A needs B, which needs C. If C fails, the exception names A at the top and C near the bottom, with each bean in between as a wrapper. Spring prints that chain in the message as Unsatisfied dependency expressed through constructor parameter 0. The practical consequence is that fixing the bean named first changes nothing, while fixing the one named last does. Search the text for the lowest Caused by and open that class.

Text
UnsatisfiedDependencyException: Error creating bean with name 'orderController': Unsatisfied dependency
  expressed through constructor parameter 0: Error creating bean with name 'orderService': ...
Caused by: BeanCreationException: Error creating bean with name 'orderRepository': ...
Caused by: ...

Turn on the report that does the reading for you

Spring Boot prints a condition evaluation report when the context fails, and it can be requested at any time. For a bean that is missing or unexpectedly present, it states which auto-configuration applied and why.

Shell
java -jar app.jar --debug 2>&1 | sed -n '/CONDITIONS EVALUATION REPORT/,/^$/p' | head -60

The report has sections for positive matches, negative matches and exclusions. For a missing DataSource, the negative matches show which condition failed, for example @ConditionalOnClass did not find required class 'org.h2.Driver'. That answers the question of why a bean was not created without reading source code.

Cut the search space with a smaller context

When the application is large, the failing bean is hidden among hundreds. Reproduce the failure with the smallest context that includes it, and fix it there. A slice test loads only the parts you name.

java
@DataJpaTest(properties = "spring.jpa.hibernate.ddl-auto=validate")
class SchemaTest {
    @Test
    void entitiesMatchTheSchema() { }
}

This test fails with the same Schema validation message in a second, with only JPA loaded, and it also serves as a guard once the migration is fixed. Pair it with Flyway or Liquibase running in the test so that the schema it validates against is the one your migrations produce, not the one Hibernate would generate for itself.

Read the order of events when the failure is intermittent

A bean creation failure that happens on some starts and not others is almost always about ordering or timing, and the chain of causes shows which. Typical examples are a bean that connects to a service at startup while the service is still booting in the same compose file, an @Value that depends on a file written by another process, and a circular dependency that resolves differently depending on the order beans are discovered. Spring Boot forbids circular references by default and reports them with the loop spelled out, which makes that case the easy one.

For a dependency on an external service, decide what the application should do when it is absent. Failing fast is correct for a database the whole application needs, and a retry on startup, for example spring.datasource.hikari.initialization-fail-timeout or Spring Cloud's fail-fast retry, covers a short delay. For an optional service, create the client lazily with @Lazy so that its absence is a runtime error on first use and not a reason the application cannot start. Writing down which dependencies are mandatory at startup, in the README next to the run instructions, saves the next engineer an hour with this exception.

Where this does not apply

If you see the exception only when running tests, a slice or a mock may be changing the context; compare with Failed to load ApplicationContext. If the trace has no Caused by below the wrapper, enable full stack traces: some logging configurations trim them. The Spring reference documents the lifecycle callbacks that can throw. The Spring Framework API documentation documents the behavior in detail.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.