BackendBench
Coffee

Home โ€บ Java exceptions โ€บ NoSuchBeanDefinitionException

Unchecked exception ยท org.springframework.beans.factory

NoSuchBeanDefinitionException: causes and fixes

Spring could not find a bean of the requested type or name to inject.

What it looks like

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.acme.OrderService' available: expected at least 1 bean which qualifies as autowire candidate

Extends BeansException in org.springframework.beans.factory.

What it means

The application context has no bean that matches an injection point (a constructor argument, an @Autowired field) or a lookup by type or name. During startup you usually see it wrapped in UnsatisfiedDependencyException, and the "Description / Action" block of the Spring Boot failure analysis states the type and often suggests the fix. It means the bean was never registered, not that it is null.

Common causes

How to fix it

  1. Annotate the class or add a @Bean method, and check that it is in a scanned package.
  2. Move the main class to the root package, or add @ComponentScan / scanBasePackages.
  3. Check active profiles and properties that the conditions depend on.
  4. Add the starter or library whose auto-configuration provides the bean.

Broken and fixed

fails
public class OrderService { }  // no annotation: not a bean

@Autowired OrderService orders; // fails
works
@Service
public class OrderService { }

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

Run with --debug to print the auto-configuration report, which lists conditions that matched and those that did not, a quick way to see why a bean is missing.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is NoSuchBeanDefinitionException a checked or unchecked exception?

NoSuchBeanDefinitionException is an unchecked exception (it extends BeansException, which is a RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is NoSuchBeanDefinitionException in?

It lives in org.springframework.beans.factory, so the import is import org.springframework.beans.factory.NoSuchBeanDefinitionException;.

What is the first thing to check when I see NoSuchBeanDefinitionException?

Read the message and the first stack trace line in your own code. The usual causes are: The class is missing a stereotype annotation (@Service, @Component, @Repository) or an @Bean method; and The class is outside the packages scanned from the @SpringBootApplication class.

Related exceptions

More tools you might need