How to Fix No Qualifying Bean Error in Spring Boot
No qualifying bean error in Spring Boot happens when the framework cannot find a bean to inject for a dependency. To fix it, ensure your bean is properly annotated (like @Component or @Service) and that component scanning includes its package, or define the bean explicitly in a configuration class.Why This Happens
This error occurs because Spring tries to inject a bean but cannot find any matching bean definition in its context. This usually happens when the class you want to inject is not annotated as a Spring bean or is outside the component scan path.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class UserService { // Service logic } @Component public class UserController { @Autowired private UserService userService; }
The Fix
Make sure the class you want to inject is annotated with @Component, @Service, or another stereotype annotation. Also, confirm your main application class scans the package containing the bean. Alternatively, define the bean explicitly in a configuration class using @Bean.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; @Configuration public class AppConfig { @Bean public UserService userService() { return new UserService(); } } @Component public class UserController { @Autowired private UserService userService; }
Prevention
To avoid this error, always annotate your service or component classes properly and keep them inside packages scanned by Spring Boot (usually under the main application package). Use constructor injection instead of field injection for better clarity and easier testing. Also, enable IDE inspections or linting tools that warn about missing bean annotations.
Related Errors
Other similar errors include NoSuchBeanDefinitionException when a bean is missing, or BeanCurrentlyInCreationException caused by circular dependencies. Fix these by checking bean definitions and avoiding circular references.