Search code examples
javaspring-bootunit-testingconfigurationmicroservices

UnsatisfiedDependencyException: No qualifying bean of type 'XXX' available


This is a Spring Boot project. My project is having another project as a dependency. Like this: SecurityConfig(my project) extends AbstractSecurityConfig(dependency project)

And this is the AbstractSecurityConfig code part:

public abstract class AbstractSecurityConfig {

    private SatValidationConfiguration satValidationConfiguration;

    @Autowired
    private SatConfig satConfig;

And this is the SatConfig (dependency project) code part.

@Lazy
@Component
public class SatConfig {

    @Value("${satKeysDir:/etc/satKeys}")
    private String satKeysDir;

    @Value("${pubSatKeys:test.pub}")
    private List<String> pubSatKeys;

    @Value("${pubSatKeysUrl:https://sat-prod.codebig2.net/keys}")
    private String pubSatKeysUrl;

    @Value("${satGracePeriod:1000}")
    private int satGracePeriod;

    private KeyResolverV1 keyResolver;

    @PostConstruct
    public void init() throws Exception {
        final File keyFolder = new File(satKeysDir);
        keyFolder.mkdirs();
        .....
    }
    .....
}

I tried unit testing.

But all unit tests are failing. I'm encountering an issue with my Spring application where I'm getting an UnsatisfiedDependencyException with the following error message:

Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'satConfig'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.yyy.SatConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I have a class SatConfig that is annotated with @Component and has the necessary @Value annotations to inject properties. However, it seems that Spring is unable to find a qualifying bean of type SatConfig during the bean creation process.

  • Verified that the SatConfig class is being scanned by Spring. The package containing SatConfig is included in the component scan configuration.

    @EnableScheduling
    @EnableCaching
    @EnableConfigurationProperties()
    @SpringBootApplication(
        scanBasePackageClasses = Application.class,
        scanBasePackages = {
            "com.xxx.my_project",
            "com.yyy.dependency_project"
        })
    public class Application extends AbstractApplication implements WebMvcConfigurer {
    
  • Verified that the necessary dependencies for SatConfig are available and properly configured as beans.

    @Lazy
    @Component
    public class SatConfig {
    

Solution

  • You can define SatConfig as Bean at the Test file separately. Clone the class to the test folder and use @TestConfiguration annotation. Then Spring Boot will see the bean at the test. Also you can define separate properties file for test. It solved for me.