The error message "No qualifying bean of a type found for dependency" typically arises when using the Spring framework, and it means that Spring's IoC container cannot find an appropriate bean to inject for a particular dependency. In this post, we will share some common solutions to this error.
The error occurs when:
Ensure that the class you want to inject is annotated with @Component
or
another stereotype
annotation like @Service
, @Repository
, or
@Controller
.
Ensure your @SpringBootApplication
or @ComponentScan
annotation is in the right
package to scan the package containing your beans.
In case auto scanning is not picking up your component, you can define the bean explicitly in a Configuration
class:
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
If there are multiple beans of the same type, you can use the @Qualifier annotation to specify which bean to autowire.
@Autowired
@Qualifier("beanName")
private MyBean myBean;
If you are still getting the same issue then try the below solutions as well:
If you're using Spring Profiles, ensure that the right profile is active if the bean is defined under a specific profile.
If the bean you're trying to inject is part of an external library, ensure that the library is correctly added as a dependency, and its components are being scanned.
Prefer constructor injection over field injection. It's more evident when a class has dependencies, and it can also help avoid some issues related to circular dependencies.
@Service
public class MyService {
private final MyBean myBean;
@Autowired
public MyService(MyBean myBean) {
this.myBean = myBean;
}
}
Ensure that you don't have conflicting versions of Spring or related libraries. Dependency conflicts can sometimes cause unexpected behaviors.
The error message often provides the exact bean type it's trying to inject. Double-check that you haven't made a typo or incorrect package reference.
By thoroughly going through these checks and understanding the root cause, you can address the "No qualifying bean of a type found for dependency" error and ensure your Spring components wire up correctly.