How to Fix UnsatisfiedDependencyException in Spring Boot

org.springframework.beans.factory.UnsatisfiedDependencyException means Spring could not supply a dependency required by a bean, usually because the dependency is missing, multiple beans match, or the selected bean failed during creation. The exception is usually a wrapper, so the useful diagnosis comes from the nested Caused by: messages. Match the underlying error to the likely repair before changing annotations.

Nested Error or Symptom Likely Cause Fix
NoSuchBeanDefinitionException or “No qualifying bean” No eligible bean exists in the current context Check registration, scanning, profiles, and imported configuration
NoUniqueBeanDefinitionException or “expected single matching bean but found…” Multiple candidates match the requested type Select a candidate with a qualifier or establish an intentional default
“Factory method threw exception” or “Constructor threw exception” The dependency exists, but its creation failed Fix the exception inside the constructor or factory method
“Could not resolve placeholder” or a configuration-binding error Required configuration is missing or invalid Correct the property source, name, or value
BeanCurrentlyInCreationException Often a circular dependency Refactor the dependency cycle
ClassNotFoundException or NoClassDefFoundError A runtime class is unavailable, or class initialization failed Inspect the nested cause, packaged dependencies, and classloader
Failure only in a Spring test The test loads a narrower context than the application Supply the intended test collaborators or use the appropriate test scope

What UnsatisfiedDependencyException Means

Spring creates and connects objects called beans. When it creates a bean, it must resolve that bean’s required constructor arguments, injected fields, setter arguments, or factory-method parameters.

For example, a controller might require a service, which requires a formatter:

ReportController → ReportService → ReportFormatter

If Spring cannot obtain ReportFormatter, it may report failures for both reportService and reportController. Those messages describe a dependency chain, not necessarily separate problems.

The bean named at the top is often affected by the failure, not the bean you need to change.

The Caused by: prefix is Java’s way of displaying a nested exception. It is not part of the exception’s class name, and the line containing UnsatisfiedDependencyException alone does not identify the correct fix.

How to Fix the Spring Dependency Error

Identify the actionable cause, then ensure the requested dependency is registered in the failing application context and included by component scanning or configuration.

Step 1: Find the Actionable Cause

  1. Capture the complete exception from the failed startup or test, rather than just the final console lines.
  2. Follow the Caused by: chain and record the requested dependency type, the injection point, and the deepest useful error.
  3. If startup produces additional shutdown errors, keep the original creation failure separate from errors caused by the context closing.

A shortened cause chain might look like this:

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'reportController':
Unsatisfied dependency expressed through constructor parameter 0
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'reportService':
Unsatisfied dependency expressed through constructor parameter 0
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.example.reports.ReportFormatter' available

Here, the actionable problem is the missing ReportFormatter bean. Changing the controller will not register that formatter.

Constructor parameter indexes are zero-based, so parameter 0 means the first constructor parameter. For field injection, the message normally identifies the field instead.

Do not interpret “deepest cause” mechanically. A database connection error, an invalid repository query, or a failure inside application code may need the surrounding exception messages to identify which bean and configuration produced it.

Step 2: Check Bean Registration and Discovery

  1. Find the class or configuration that should provide the requested type.
  2. Confirm that it registers a bean in the application context that is failing.
  3. Check whether component scanning or imported configuration actually includes it.

For a concrete service implementation discovered through component scanning, put @Service on the implementation class. Annotating only an ordinary interface does not give Spring a concrete object to instantiate.

For example, these types belong in separate Java files:

package com.example.reports;
public interface ReportFormatter {
    String format(String title);
}
package com.example.reports;
import org.springframework.stereotype.Service;
@Service
public class PlainTextReportFormatter implements ReportFormatter {
    @Override
    public String format(String title) {
        return "Report: " + title;
    }
}

If you cannot annotate the implementation, for example, because it comes from a library, provide it through an @Bean method in a configuration class that the context loads. Use one intentional registration mechanism rather than accidentally registering the same implementation twice.

Next, check the application configuration class. @SpringBootApplication enables component scanning from its package downward by default. An application class in com.example can discover the example implementation in com.example.reports; an application class in the sibling package com.example.application does not discover it through that default scan.

Place the application configuration in a common parent package, or explicitly configure scanning or imports for the intended components. Avoid scanning unrelated packages merely to make startup succeed.

Some bean types use different registration mechanisms:

  • Spring Data repositories need the appropriate repository infrastructure and repository scanning, not a stereotype annotation added to an interface.
  • JPA entities are not service beans; entity discovery is separate from component scanning.
  • Auto-configured library beans depend on their configuration conditions being satisfied.

The important question is not whether a class exists in the project. It is whether an eligible bean of the requested type exists in this context.

Step 3: Check Constructor Selection and Candidate Selection

  1. Inspect the injection point named in the exception.
  2. Confirm that Spring can choose the intended constructor.
  3. If multiple beans match, make the intended selection explicit.

For a Spring-managed bean with a single constructor, Spring supports constructor injection without an annotation. When constructor selection needs to be explicit, such as a class with multiple constructors, put @Autowired on the intended constructor.

Adding that annotation does not create missing dependencies.

When multiple implementations match, use a qualifier to identify the appropriate candidate. For example, this service selects the formatter registered under its default bean name, plainTextReportFormatter:

package com.example.reports;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class ReportService {
    private final ReportFormatter formatter;
    public ReportService(
            @Qualifier("plainTextReportFormatter")
            ReportFormatter formatter) {
        this.formatter = formatter;
    }
    public String render(String title) {
        return formatter.format(title);
    }
}

Import org.springframework.beans.factory.annotation.Qualifier, not a similarly named annotation from an unrelated library.

If an implementation should be the default for otherwise unqualified, single-valued injection points, marking that bean @Primary can be appropriate instead. Use that only when the default makes sense across its consumers; use a qualifier when the choice belongs to a particular consumer.

A qualifier narrows candidates of the required type. It cannot make an unregistered bean exist, and an incorrect qualifier can exclude an otherwise valid candidate.

Also distinguish Spring-managed objects from objects created manually. An object constructed with new is not automatically managed by Spring, so its annotated fields are not automatically injected.

Step 4: Repair Dependency Creation and Retry

  1. If the dependency is registered but cannot be created, inspect its own constructor, factory method, configuration binding, or initialization callback.
  2. Apply the repair indicated by that underlying exception.
  3. Rebuild changed code, restart the failing application or rerun the failing test, and exercise the operation that uses the dependency.

Common repairs require looking beyond dependency-injection annotations:

  • Application code throws during construction: Find the first relevant application-code frame in the trace. Correct the invalid argument, failed assumption, or initialization logic.
  • Configuration cannot be resolved or bound: Check the property name, the configuration source used by that process, and the expected Java type. Supply the intended value without exposing secrets in logs or source control.
  • Database or repository initialization fails: Test connectivity from the application’s runtime environment and inspect the database-specific error. Correct authentication, schema, mapping, or repository-query problems as indicated.
  • A runtime class is missing: Inspect the resolved dependency graph and packaged application. Check dependency scope and version alignment rather than adding arbitrary JARs. In Spring Boot projects, prefer compatible dependencies managed by the project’s Boot version unless an override is deliberate.
  • A class could not initialize: With a message such as NoClassDefFoundError: Could not initialize class, look for an earlier initialization exception. Adding another copy of the class may not address the failure.

A clean build removes stale compiled output; it does not repair a missing bean definition or invalid configuration.

If the next run exposes a different dependency failure, diagnose that new cause rather than continuing to change the original injection point.

When It Fails Only in Tests or One Environment

Compare the failing test or environment with the working configuration to find beans excluded by narrow contexts, profiles, conditions, packaging, or reload.

Narrow Test Contexts

A test can fail even when production startup works because it deliberately loads fewer beans. For example, @WebMvcTest focuses on the web layer and does not normally discover arbitrary service implementations.

A plain Mockito @Mock does not automatically become a bean in the Spring application context.

Use @SpringBootTest when the test genuinely needs the application’s broader wiring, not simply to hide a missing collaborator in a focused test. Rerun the affected test and verify its assertions, rather than stopping at successful context creation.

Profiles and Conditional Configuration

A bean can be present in the codebase but absent from a particular run because of @Profile, conditional configuration, or excluded auto-configuration.

Compare the failing process’s active profiles and effective configuration with the working environment. Check the condition evaluation report when an expected auto-configured bean is absent; it can explain which condition prevented registration.

Activate the configuration intended for that environment, or provide an implementation appropriate to it. Restart using that environment’s actual launch configuration and test the dependent operation. Do not remove a profile restriction merely because doing so makes a local run pass.

Packaged Applications and Hot Reload

If the application works in an IDE but fails from its packaged artifact, compare the runtime contents and configuration sources. A dependency available during compilation may be excluded from the deployed artifact or expected to be supplied by the application server.

Application-server classloader isolation can also hide a class that exists somewhere in the deployment. This matters especially when failures occur only during hot reload or after a reload agent attempts to refresh Spring components.

Disable the reload mechanism and perform a full application or server restart to establish a baseline. If normal startup works, keep reload disabled while checking agent compatibility and classloader configuration; then verify the application operation that previously failed. Adding duplicate Spring libraries can introduce new linkage problems instead of fixing visibility.

How to Resolve Circular Dependencies

A circular dependency occurs when following required dependencies leads back to a bean already being created:

OrderService → PaymentService → OrderService

With constructor injection, Spring cannot finish constructing either bean without first obtaining the other. The trace may include BeanCurrentlyInCreationException or wording that the requested bean is currently in creation.

To repair the cycle:

  1. Draw the dependency chain from the exception and identify the responsibilities that point back at each other.
  2. Refactor those responsibilities so the graph has a clear direction. A shared collaborator can own common logic, or a coordinating service can call both components.
  3. Update constructor dependencies, run the affected tests, and start the application to verify both wiring and behavior.

Do not switch to field injection merely to conceal the design problem. Likewise, enabling circular-reference support is not a general solution and does not make constructor cycles resolvable.

Lazy resolution can be appropriate when a dependency genuinely should be obtained later, but it requires checking the lifecycle carefully. If initialization immediately calls through the lazy dependency, the underlying problem may remain.

How to Verify and Prevent Wiring Failures

A successful context refresh is necessary, but lazy initialization can defer some failures until a request, scheduled job, or event uses the bean.

Confirm the repair with this checklist:

  • The intended application or test context starts successfully.
  • The affected request, job, or method completes successfully.
  • The selected implementation matches the environment’s intended behavior.
  • The fix has not disabled a required feature or replaced a production dependency with a local substitute.

To reduce recurrence, keep constructor dependencies explicit, place configuration and components in predictable packages, and test important profile-specific configurations. Test slices should declare their required collaborators, while integration tests should cover the relevant application wiring.

If the failure remains, collect the complete cause chain, the affected constructor or injection point, the bean registration code, active profiles, and dependency versions. Remove credentials and other secrets before sharing those details for further diagnosis.

Frequently Asked Questions

What Causes BeanCreationException in Spring Boot?

BeanCreationException means Spring failed while creating or initializing a bean. Causes include exceptions in constructors or factory methods, invalid configuration, failed initialization callbacks, and dependencies that cannot be resolved. UnsatisfiedDependencyException is a subclass that specifically identifies a failure to satisfy a dependency.

What Does “A Component Required a Bean of Type CacheManager That Could Not Be Found” Mean?

The missing CacheManager message means the current Spring context has no eligible bean implementing org.springframework.cache.CacheManager for the injection point. For an intentionally local, in-memory cache, this configuration enables annotation-driven caching and supplies a manager:

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfiguration {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager();
    }
}

Place this configuration where Spring discovers or imports it; if a shared provider such as Redis is intended, repair that provider’s dependencies and configuration instead of silently substituting local storage. Restart and exercise a cached method through its Spring-managed bean to confirm caching behavior, not merely successful startup.

Can I Fix This by Making the Dependency Optional?

Making a dependency optional is appropriate only when the component can function correctly without it. Optional<T> or ObjectProvider<T> can express optional or deferred access, but they do not repair a broken required dependency. If absence is intentional, implement and test both the dependency-present and dependency-absent behavior before accepting the change.