Skip to content
javahacks.dev
Spring Framework

Fix NoSuchBeanDefinitionException in Spring Applications

Fix NoSuchBeanDefinitionException by telling apart a missing type, a missing name and a bean hidden by scanning, profiles or a child context.

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

A Spring application starts, then dies in the first second with this:

Text
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'dev.javahacks.shop.PaymentGateway' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

Or a getBean("paymentGateway") call fails with No bean named 'paymentGateway' available. The container is telling you it was asked for something it never registered. That is almost always one of five causes, and they are quick to tell apart if you check them in the right order. This post walks through each on Spring Framework 7 and shows the fix with code. If the message instead says more than one bean matched, that is a different exception, covered in NoUniqueBeanDefinitionException and qualifiers.

Read which form of the message you have

The exception has two messages and they mean different lookups.

Message starts withLookupTypical trigger
No qualifying bean of type 'X' availableBy typeConstructor, @Autowired or getBean(X.class)
No bean named 'x' availableBy namegetBean("x"), @Qualifier("x"), @DependsOn("x")

A type lookup that fails also prints expected at least 1 bean which qualifies as autowire candidate. If you see expected single matching bean but found 2, you are in the other exception. The sibling error where the bean exists but its own construction failed is BeanCreationException, described in BeanCreationException and its root cause. Reading the first line carefully saves a lot of searching.

Check that the class is registered at all

A class is a bean only if something registers it. For component scanning that means an annotation (@Component, @Service, @Repository) on a class inside a scanned package. The classic miss is a package outside the one holding the @SpringBootApplication class:

src/main/java/dev/javahacks/shop/ShopApplication.javajava
package dev.javahacks.shop;

@SpringBootApplication
public class ShopApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}
src/main/java/dev/javahacks/payments/StripeGateway.javajava
package dev.javahacks.payments;   // not under dev.javahacks.shop

@Service
class StripeGateway implements PaymentGateway { }

Scanning starts at dev.javahacks.shop, so dev.javahacks.payments is never visited and PaymentGateway has no bean. Confirm it by listing what the container actually holds:

java
@Bean
ApplicationRunner listBeans(ApplicationContext ctx) {
    return args -> Arrays.stream(ctx.getBeanNamesForType(PaymentGateway.class))
            .forEach(System.out::println);
}
Text
(no output)

No output means no bean of that type. The fix is either to move the class under the scanned package or to widen the scan deliberately:

java
@SpringBootApplication(scanBasePackages = {"dev.javahacks.shop", "dev.javahacks.payments"})

An annotation on an interface is also a miss. @Service on PaymentGateway registers nothing, since an interface cannot be instantiated; annotate the implementation. In a plain Spring app with Java configuration, make sure the @Configuration class that declares the bean is itself picked up, through @Import or scanning. The container model behind this is explained in how the Spring container really works.

Work out the bean name Spring derived

For a name lookup, the name you typed has to match the name Spring chose. The rules are small:

  • A scanned class gets its simple name with the first letter lowercased: StripeGateway becomes stripeGateway.
  • A @Bean method gives its method name: paymentGateway() becomes paymentGateway.
  • An explicit value wins: @Service("stripe") or @Bean("stripe").

There is a famous exception in the rule. When the first two letters are both uppercase, as in URLResolver, Spring keeps the name unchanged (URLResolver), because the JavaBeans decapitalize rule leaves it alone. Asking for uRLResolver fails.

Print the names to stop guessing:

java
String[] names = ctx.getBeanDefinitionNames();
Arrays.stream(names).filter(n -> n.toLowerCase().contains("gateway")).forEach(System.out::println);
Text
stripeGateway

Then use that exact string, or better, stop looking up by name altogether (more on that below).

Ask the right context

A bean is visible in the context that registered it and in that context's children, never the other way. Web applications often have a root context and a child servlet context, and a bean defined in the child cannot be fetched from the parent.

java
// Root context lacks 'viewResolver' even though the web context has it
AnnotationConfigApplicationContext root = new AnnotationConfigApplicationContext(RootConfig.class);
root.getBean("viewResolver");   // throws NoSuchBeanDefinitionException

In Spring Boot a single context is the norm, so this mostly bites older XML or DispatcherServlet setups and tests that build a second context by hand. When it does, either register the bean in the parent or inject through the child. A ListableBeanFactory call with BeanFactoryUtils.beansOfTypeIncludingAncestors searches upward and is occasionally the right tool for library code.

Look for an inactive profile or a failed condition

A bean can exist in the source and not in the container. @Profile("prod") skips it unless that profile is active, and @ConditionalOnProperty, @ConditionalOnClass and @ConditionalOnMissingBean can all decline silently.

java
@Service
@Profile("prod")
class StripeGateway implements PaymentGateway { }

Run with --spring.profiles.active=dev and any consumer of PaymentGateway fails. Check which profiles are live and why a conditional was skipped. Spring Boot gives you the condition evaluation report on request:

Shell
java -jar target/shop.jar --debug
Text
Negative matches:
-----------------
   StripeGateway:
      Did not match:
         - @Profile specifies 'prod' but the following profiles are active: dev

The fix is to provide a bean for every profile that needs one, such as a FakePaymentGateway under @Profile("!prod"), so no environment is left without an implementation. The same report is the best tool for starters: if an expected auto-configured bean is missing, its Negative matches entry names the missing class or property.

Check the declared type, not just the class

Injection by type looks at the bean's declared type. A @Bean method that returns Object, or a raw supertype, hides the real type from the lookup:

java
@Bean
Object paymentGateway() {            // declared as Object
    return new StripeGateway();
}

At the point of injection Spring may not have created the bean yet, so it trusts the signature, and PaymentGateway does not match Object. Declare the most specific useful return type: PaymentGateway paymentGateway(). Generics follow the same rule, so a Repository<Order> is not a match for a Repository<Invoice> injection point. And a final class proxied for @Transactional is not an option under class-based proxying, which turns up as a related creation error rather than this one.

Make a missing bean optional only when it truly is

Sometimes absence is legitimate, for example an optional metrics integration. Say so in the code instead of catching the exception:

java
@Service
class CheckoutService {

    private final PaymentGateway gateway;
    private final Optional<FraudCheck> fraud;

    CheckoutService(PaymentGateway gateway, ObjectProvider<FraudCheck> fraud) {
        this.gateway = gateway;
        this.fraud = Optional.ofNullable(fraud.getIfAvailable());
    }
}

ObjectProvider defers the lookup and returns null or a default instead of throwing. Use it for genuinely optional collaborators only. Making a required dependency optional to silence the error moves the failure to a NullPointerException at runtime, which is harder to find.

Prefer injection to lookup

Calling getBean("name") pushes a runtime failure into code that the compiler cannot check. Constructor injection of the type fails at startup, in one place, with the message above, which is the earlier and cheaper failure. Reach for ApplicationContext.getBean only in framework glue, in a factory choosing among beans at runtime, or in tests. The reference for naming and registration is in the Spring bean definition documentation, and the API is in the Javadoc. The sibling message for a missing type in injection points is dissected in No qualifying bean of type.

Where this does not apply

If the stack trace shows the bean exists but a nested cause failed, you have a BeanCreationException, and the fix lies in the cause at the bottom of the trace, not in scanning. If you are on Spring Boot with a starter that should auto-configure the bean, the missing piece is usually a dependency or a property, and the --debug report is the faster route than reading your own code. And in a native image, a bean registered by reflection may need runtime hints, which fails differently and only after the AOT build.

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.