Skip to content

Fix: Spring BeanCreationException: Error creating bean with name

FixDevs · (Updated: )

Part of:  Java & JVM Errors

Quick Answer

How to fix Spring BeanCreationException error creating bean caused by missing dependencies, circular references, wrong annotations, configuration errors, and constructor issues.

The Error

Your Spring Boot application fails to start with:

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myService': Injection of autowired dependencies failed

Or variations:

Error creating bean with name 'myController' defined in file [...]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.example.MyRepository' available
Error creating bean with name 'dataSource': Failed to determine a suitable driver class
Error creating bean with name 'entityManagerFactory':
Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException
BeanCurrentlyInCreationException: Error creating bean with name 'serviceA':
Requested bean is currently in creation: Is there an unresolvable circular reference?

Spring’s dependency injection container (ApplicationContext) cannot create one or more beans. The root cause is always in the nested exception message.

Why This Happens

Spring creates and wires beans during application startup. When a bean cannot be created, the entire context fails. The BeanCreationException is a wrapper around the actual problem.

The bootstrap sequence has three phases that can each fail: (1) component scanning discovers candidate classes; (2) the bean definition is materialised into an instance, usually by calling the constructor or @Bean factory method; (3) dependencies are wired and @PostConstruct / InitializingBean hooks run. The exception you see almost always identifies the phase that exploded, but the wrapped message is what tells you what to fix. Reading from the bottom of the stack trace to the top is essential, because every layer of Spring adds its own wrapper.

A second mental model that helps: Spring tracks every bean it is currently creating. When it sees a request for a bean already on that “in-progress” list, it raises BeanCurrentlyInCreationException. That is how circular dependencies are detected. The same mechanism is what changed in Spring 6 to forbid the cycle outright unless you opt in.

Common causes:

  • Missing bean dependency. A @Service or @Repository is not found by component scanning.
  • Circular dependency. Bean A depends on Bean B, which depends on Bean A.
  • Wrong configuration. Database URL, missing properties, or invalid YAML.
  • Missing annotation. A class needs @Component, @Service, or @Repository but does not have one.
  • Constructor mismatch. The constructor requires parameters that Spring cannot provide.
  • Profile not active. A bean is conditional on a profile that is not enabled.
  • Database connection failure. DataSource cannot connect to the database.

Version History That Changes the Failure Mode

Spring Framework and Spring Boot have made several breaking changes that turn previously-working code into bean creation failures. If you upgraded recently, the version pivot is often the entire cause.

  • Spring Framework 5.0 (Sep 2017) and Spring Boot 2.0 (Mar 2018). The “classic” reference point. Field injection with @Autowired was discouraged but still worked everywhere, circular dependencies resolved themselves silently, and javax.* was the standard namespace.
  • Spring Framework 5.3 (Oct 2020) / Spring Boot 2.6 (Nov 2021). Spring Boot 2.6 disabled circular references by default. Bumping to 2.6 from 2.5 is the single most common reason a previously-working app suddenly throws BeanCurrentlyInCreationException. The opt-in switch is spring.main.allow-circular-references=true, but that is a temporary escape hatch, not a fix.
  • Spring Framework 6.0 / Spring Boot 3.0 (Nov 2022). Two breaking changes hit at once. First, the baseline became Java 17, so apps on Java 8 or 11 cannot upgrade until the JDK is bumped. Second, the entire javax.* namespace moved to jakarta.* (Jakarta EE 9). Any third-party library still importing javax.servlet, javax.persistence, or javax.validation will fail to wire because the bean signatures no longer match. This is why so many “BeanCreationException after upgrading to Spring Boot 3” reports exist for libraries that have not yet released a Jakarta-compatible version.
  • Spring Framework 6.1 / Spring Boot 3.2 (Nov 2023). Virtual thread support landed. @Async and Servlet thread handling can now run on virtual threads. Bean wiring is unchanged, but if you turn this on, certain ThreadLocal-heavy beans may fail in ways that surface as init-method errors.
  • Spring Framework 6.2 / Spring Boot 3.3 (2024). Improved @ConfigurationProperties validation and stricter property binding. Properties that previously coerced loosely (for example, an empty string into an int) now fail at bean creation rather than silently producing a zero value.
  • Spring Boot 3.4+ (late 2024 onward). Tighter defaults around spring.jpa.open-in-view, observability auto-wiring, and Micrometer integration. Several beans that used to be lazily created are now eager, which means latent misconfigurations surface at startup as BeanCreationException rather than at first request.

If you maintain an older Spring Boot 2 app and start a new project on 3.x, do not assume the bean wiring rules are the same. Constructor injection is now the only recommended style, @Autowired on fields is actively discouraged, and any javax.* import is a red flag.

Fix 1: Fix Missing Bean Dependencies

The most common cause. Spring cannot find a bean to inject:

No qualifying bean of type 'com.example.MyRepository' available

Check the class has a stereotype annotation:

// Missing annotation — Spring doesn't know about this class!
public class MyRepository {
    // ...
}

// Fixed — add @Repository
@Repository
public class MyRepository {
    // ...
}

Common annotations:

AnnotationUse for
@ComponentGeneric bean
@ServiceBusiness logic
@RepositoryData access
@Controller / @RestControllerWeb endpoints
@ConfigurationConfiguration classes

Check component scanning covers the package:

@SpringBootApplication  // Scans this package and sub-packages
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

@SpringBootApplication scans the package it is in and all sub-packages. If your beans are in a different package tree, add @ComponentScan:

@SpringBootApplication
@ComponentScan(basePackages = {"com.example.app", "com.example.shared"})
public class MyApplication { }

Pro Tip: Keep your @SpringBootApplication class in the root package (e.g., com.example.app) so all sub-packages are scanned automatically. This avoids most component scanning issues.

Fix 2: Fix Circular Dependencies

Spring 6 / Spring Boot 3 disallows circular dependencies by default:

BeanCurrentlyInCreationException: Requested bean is currently in creation:
Is there an unresolvable circular reference?

Broken — circular dependency:

@Service
public class ServiceA {
    private final ServiceB serviceB;

    public ServiceA(ServiceB serviceB) {
        this.serviceB = serviceB;
    }
}

@Service
public class ServiceB {
    private final ServiceA serviceA;

    public ServiceB(ServiceA serviceA) {
        this.serviceA = serviceA;
    }
}

Fixed — use @Lazy on one dependency:

@Service
public class ServiceA {
    private final ServiceB serviceB;

    public ServiceA(@Lazy ServiceB serviceB) {
        this.serviceB = serviceB;
    }
}

Fixed — refactor to remove the cycle:

// Extract shared logic into a third service
@Service
public class SharedService {
    // Logic that both ServiceA and ServiceB need
}

@Service
public class ServiceA {
    private final SharedService shared;
    public ServiceA(SharedService shared) { this.shared = shared; }
}

@Service
public class ServiceB {
    private final SharedService shared;
    public ServiceB(SharedService shared) { this.shared = shared; }
}

Fixed — use events for loose coupling:

@Service
public class ServiceA {
    private final ApplicationEventPublisher publisher;

    public ServiceA(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public void doWork() {
        publisher.publishEvent(new WorkCompletedEvent(this));
    }
}

@Service
public class ServiceB {
    @EventListener
    public void onWorkCompleted(WorkCompletedEvent event) {
        // React to ServiceA's event without a direct dependency
    }
}

For more focused treatment of the circular case, see Fix: Spring circular dependency.

Common Mistake: Enabling spring.main.allow-circular-references=true as a quick fix. This hides a design problem. Circular dependencies indicate tightly coupled code. Refactor instead.

Fix 3: Fix Database Configuration

If the error mentions dataSource, entityManagerFactory, or database drivers:

Failed to determine a suitable driver class

Check application.properties or application.yml:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Check the database driver is in your dependencies:

<!-- pom.xml -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>
// build.gradle
runtimeOnly 'com.mysql:mysql-connector-j'

Check the database is running:

mysql -u root -p -h localhost -P 3306

If you do not need a database yet:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication { }

Or in application.properties:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

For the more specific Failed to configure a DataSource startup message, see Fix: Spring Boot Failed to configure a DataSource.

Fix 4: Fix Constructor Injection Issues

Spring needs to resolve all constructor parameters:

Broken — constructor has parameters Spring cannot provide:

@Service
public class MyService {
    private final String apiKey;
    private final MyRepository repo;

    public MyService(String apiKey, MyRepository repo) {
        this.apiKey = apiKey;  // Spring doesn't know how to inject a plain String!
        this.repo = repo;
    }
}

Fixed — use @Value for configuration properties:

@Service
public class MyService {
    private final String apiKey;
    private final MyRepository repo;

    public MyService(@Value("${api.key}") String apiKey, MyRepository repo) {
        this.apiKey = apiKey;
        this.repo = repo;
    }
}

With application.properties:

api.key=your-api-key-here

Fixed — use @ConfigurationProperties for complex config:

@ConfigurationProperties(prefix = "api")
public record ApiConfig(String key, String baseUrl, int timeout) {}

@Service
public class MyService {
    private final ApiConfig config;
    private final MyRepository repo;

    public MyService(ApiConfig config, MyRepository repo) {
        this.config = config;
        this.repo = repo;
    }
}

Fix 5: Fix Conditional and Profile Bean Issues

A bean might only be available under certain conditions:

@Service
@Profile("production")
public class ProductionEmailService implements EmailService { }

@Service
@Profile("dev")
public class MockEmailService implements EmailService { }

If you run without specifying a profile, neither bean is created:

# application.properties
spring.profiles.active=dev

Or set it on the command line:

java -jar myapp.jar --spring.profiles.active=dev

Check for @ConditionalOnProperty:

@Service
@ConditionalOnProperty(name = "feature.email.enabled", havingValue = "true")
public class EmailService { }

If the property is missing or false, the bean is not created.

Fix 6: Fix Multiple Bean Candidates

When Spring finds multiple beans of the same type:

No qualifying bean of type 'com.example.PaymentService' available:
expected single matching bean but found 2: stripeService,paypalService

Fixed — use @Primary:

@Service
@Primary
public class StripeService implements PaymentService { }

@Service
public class PaypalService implements PaymentService { }

Fixed — use @Qualifier:

@Service
public class OrderService {
    private final PaymentService payment;

    public OrderService(@Qualifier("stripeService") PaymentService payment) {
        this.payment = payment;
    }
}

Fixed — inject a collection:

@Service
public class OrderService {
    private final List<PaymentService> paymentServices;

    public OrderService(List<PaymentService> paymentServices) {
        this.paymentServices = paymentServices;  // Gets all implementations
    }
}

Fix 7: Fix Init Method Failures

If the error says “Invocation of init method failed”:

@Service
public class CacheService {
    @PostConstruct
    public void init() {
        // This method runs after bean creation
        // If it throws, BeanCreationException wraps the error
        loadCache();  // Might fail if external service is down
    }
}

Fixed — handle init failures gracefully:

@PostConstruct
public void init() {
    try {
        loadCache();
    } catch (Exception e) {
        log.warn("Cache pre-loading failed, will load on demand", e);
    }
}

Or use @EventListener for non-critical initialization:

@EventListener(ApplicationReadyEvent.class)
public void onReady() {
    // Runs after the application is fully started
    loadCache();
}

Fix 8: Read the Full Stack Trace

The BeanCreationException wraps the real error. Read the full stack trace from bottom to top:

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'orderService'
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.example.PaymentGateway'
...
Caused by: java.lang.ClassNotFoundException: com.stripe.Stripe

The last “Caused by” is the root cause. In this example, the Stripe SDK class is missing from the classpath — add the dependency.

Enable debug logging for more context:

logging.level.org.springframework=DEBUG

Or start with the --debug flag:

java -jar myapp.jar --debug

Still Not Working?

Check for version mismatches. Mixing Spring Boot 2.x and 3.x dependencies causes bean creation failures. Use the Spring Boot BOM to manage versions:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.0</version>
</parent>

Check for missing @EnableJpaRepositories. If you use Spring Data JPA with a non-standard package layout:

@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.repos")
@EntityScan(basePackages = "com.example.entities")
public class MyApplication { }

Check for @Bean method issues:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService(/* missing required parameter */);
    }
}

Check for leftover javax.* imports after a Spring Boot 3 upgrade. Any class that still imports javax.servlet.*, javax.persistence.*, or javax.validation.* will fail to satisfy the bean type that now expects jakarta.*. The compile may even succeed (because some legacy artifacts still ship javax classes), but bean wiring fails at startup. Search the codebase for import javax. and replace systematically. If the failure is on the JVM side rather than DI side, see Fix: Java UnsupportedClassVersionError: Unsupported major.minor version — Spring Boot 3 requires Java 17+, and a runtime mismatch surfaces there first.

Check that the failing bean is not a Spring AOT-incompatible class. With AOT processing or GraalVM native image, certain reflection or @Bean factory patterns silently produce missing beans at runtime even though the JIT build works. Run ./mvnw spring-boot:process-aot or the Gradle equivalent locally and inspect the generated metadata for the failing bean name.

Check for @Transactional on a private or final method. Spring’s default proxy mechanism cannot intercept those, and the resulting proxy can fail to satisfy a downstream dependency that expects the transactional interface. Make the method public and non-final, or switch to AspectJ weaving.

For dependency resolution problems that surface as missing beans because the JAR never made it onto the classpath, see Fix: Maven could not resolve dependencies.

F

FixDevs

Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.

Was this article helpful?

Related Articles