java framework_error ai_generated true

org.springframework.beans.factory.NoSuchBeanDefinitionException

ID: java/spring-bean-not-found

Also available as: JSON · Markdown
90%Fix Rate
92%Confidence
90Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
6 active

Root Cause

NoSuchBeanDefinitionException is thrown when Spring cannot find a bean definition matching the requested type or name. This typically means the class is not annotated as a Spring component, is not in a scanned package, or the configuration is missing.

generic

Workarounds

  1. 92% success Ensure the class is annotated with @Component, @Service, @Repository, or @Controller and is within a package covered by component scanning
    1. Verify the class has a Spring stereotype annotation (@Component, @Service, @Repository, @Controller, or @Configuration). 2. Check that the class's package is a sub-package of your @SpringBootApplication class's package. 3. If the class is in a different package tree, add it explicitly: @ComponentScan(basePackages = {'com.main', 'com.other'}). 4. For third-party classes, create a @Bean method in a @Configuration class to register them.
  2. 90% success Use @Bean method in a @Configuration class to explicitly define the bean when automatic scanning is not appropriate
    1. Create a @Configuration class. 2. Add a @Bean method that returns the instance: @Bean public MyService myService() { return new MyServiceImpl(); }. 3. This is the correct approach for third-party classes, conditional beans (@ConditionalOnProperty), and beans requiring complex initialization. 4. For multiple implementations of the same interface, use @Qualifier or @Primary to disambiguate.

Dead Ends

Common approaches that don't work:

  1. Creating the bean manually with 'new' instead of letting Spring manage it 80% fail

    Manually instantiating a Spring-managed class bypasses dependency injection entirely. The new instance will not have its @Autowired fields injected, @Transactional proxies will not be created, and AOP aspects will not apply. This creates a partially initialized object that fails in subtle ways.

  2. Adding @Component to a class in a package that is not covered by @ComponentScan 65% fail

    Spring only scans packages explicitly listed in @ComponentScan or sub-packages of the @SpringBootApplication class. Adding @Component to a class outside the scan path has no effect — Spring never sees the annotation.

Error Chain

Leads to:
Preceded by:
Frequently confused with: