How to Fix Bean Not Found Error in Spring Boot
bean not found error in Spring Boot happens when Spring cannot find or create a required bean. To fix it, ensure your class is annotated with @Component or similar, and that component scanning covers its package. Also, check that you inject beans correctly using @Autowired or constructor injection.Why This Happens
This error occurs because Spring Boot cannot find a bean to inject where it is needed. This usually happens when the class is not marked as a Spring-managed component or is outside the package scanned by Spring. Without a bean, Spring cannot fulfill the dependency, causing the error.
package com.example.demo.service; public class MyService { public String greet() { return "Hello"; } } package com.example.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/greet") public String greet() { return myService.greet(); } }
The Fix
To fix this, annotate MyService with @Service (or @Component) so Spring knows to create a bean. Also, ensure your main application class is in a package that scans both controller and service packages. This lets Spring find and inject the bean properly.
package com.example.demo.service; import org.springframework.stereotype.Service; @Service public class MyService { public String greet() { return "Hello"; } } package com.example.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { private final MyService myService; @Autowired public MyController(MyService myService) { this.myService = myService; } @GetMapping("/greet") public String greet() { return myService.greet(); } }
Prevention
Always annotate your classes that need to be managed by Spring with @Component, @Service, @Repository, or @Controller. Keep your packages organized so Spring Boot's component scanning covers them. Prefer constructor injection over field injection for clearer dependencies. Use your IDE or build tools to check for missing beans early.
Related Errors
Other common errors include:
- Multiple beans found: Happens when Spring finds more than one bean of the same type. Fix by using
@Qualifieror making beans unique. - Bean creation failure: Occurs if a bean's constructor throws an exception. Check constructor logic and dependencies.
- Missing configuration properties: Beans depending on config may fail if properties are missing. Verify your
application.propertiesorapplication.yml.