How to fix @Autowired – No qualifying bean of type found for dependency in Spring Boot? [Solved]

@Autowired is an annotation provided by the Spring framework, which is used to automatically wire beans together by type in a Spring Boot application. If you’re encountering the error “No qualifying bean of type found for dependency,” it usually means that Spring couldn’t find a matching bean to inject for the specified type.

Here are some common reasons for this error and their respective solutions:

  1. Missing or misplaced @Component or @Service annotation:

Make sure that the class you want to inject is annotated with either @Component, @Service, @Repository, or @Controller. This annotation indicates that the class should be managed by the Spring container and can be injected as a dependency.

Java
@Component
public class MyClass {
    // ...
}
  1. Component scan is not configured correctly:

By default, Spring Boot scans packages and sub-packages from the main application class’s package. If your bean class is in a different package, you should specify the package to be scanned using the @ComponentScan annotation in your main application class.

Java
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.myapp", "com.example.otherpackage"})
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
  1. Missing or incorrect configuration class:

If the bean is defined in a Java configuration class, make sure the class is annotated with @Configuration and the bean method with @Bean

Java
@Configuration
public class MyConfiguration {
    @Bean
    public MyClass myClass() {
        return new MyClass();
    }
}
  1. Circular dependency:

If you have a circular dependency between two beans, Spring may fail to resolve them correctly. You can use the @Lazy annotation to break the cycle.

Java
@Component
public class ClassA {
    @Autowired
    @Lazy
    private ClassB classB;
}

@Component
public class ClassB {
    @Autowired
    private ClassA classA;
}
  1. Profiles:

If you are using Spring profiles, ensure that the bean is available for the active profile. The bean could be missing due to being associated with a different profile.

If none of the above solutions work, try checking your project’s configuration and dependencies thoroughly, and ensure that you’re using compatible versions of Spring Boot and other libraries.

Leave a Comment

3 × five =