Fix: Spring BeanCreationException: Error creating bean with name
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 failedOr 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' availableError creating bean with name 'dataSource': Failed to determine a suitable driver classError creating bean with name 'entityManagerFactory':
Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceExceptionBeanCurrentlyInCreationException: 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.
Common causes:
- Missing bean dependency. A
@Serviceor@Repositoryis 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@Repositorybut 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.
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' availableCheck 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:
| Annotation | Use for |
|---|---|
@Component | Generic bean |
@Service | Business logic |
@Repository | Data access |
@Controller / @RestController | Web endpoints |
@Configuration | Configuration 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
@SpringBootApplicationclass 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
}
}Common Mistake: Enabling
spring.main.allow-circular-references=trueas 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 classCheck 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.DriverCheck 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 3306If 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.DataSourceAutoConfigurationFix 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-hereFixed — 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=devOr set it on the command line:
java -jar myapp.jar --spring.profiles.active=devCheck 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,paypalServiceFixed — 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.StripeThe 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=DEBUGOr start with the --debug flag:
java -jar myapp.jar --debugStill 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 */);
}
}For Spring Boot startup errors in general, see Fix: Spring Boot Whitelabel Error Page. For Java class loading issues, see Fix: Java ClassNotFoundException. For dependency resolution problems, see Fix: Maven could not resolve dependencies.
Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.
Was this article helpful?
Related Articles
Fix: Spring Boot Web server failed to start. Port 8080 was already in use
How to fix the Spring Boot error 'Web server failed to start. Port 8080 was already in use' by killing blocking processes, changing ports, fixing IDE issues, and resolving Docker conflicts.
Fix: Java ClassCastException: class X cannot be cast to class Y
How to fix Java ClassCastException by using instanceof checks, fixing generic type erasure, resolving ClassLoader conflicts, correcting raw types, and using pattern matching in Java 16+.
Fix: Java ConcurrentModificationException
How to fix Java ConcurrentModificationException caused by modifying a collection while iterating, HashMap concurrent access, stream operations, and multi-threaded collection usage.
Fix: Java NoSuchMethodError
How to fix Java NoSuchMethodError caused by classpath conflicts, incompatible library versions, wrong dependency scope, shaded JARs, and compile vs runtime version mismatches.