0
0
SpringbootDebug / FixBeginner · 4 min read

How to Fix No Qualifying Bean Error in Spring Boot

The 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.

java
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;
}
Output
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.UserService' available
🔧

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.

java
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;
}
Output
Application starts successfully and UserController receives UserService bean
🛡️

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.

Key Takeaways

Always annotate your classes with @Component, @Service, or @Repository to register them as beans.
Ensure your Spring Boot application scans the packages containing your beans.
Use explicit @Bean methods in @Configuration classes when automatic scanning is not suitable.
Prefer constructor injection for clearer dependencies and easier testing.
Check for circular dependencies if you encounter related bean creation errors.