oucem
oucem

Reputation: 79

@ConditionalOnProperty Bean configuration not working as expected

For a simple spring boot app I'm facing an unexpected behavior when trying to instantiate beans conditionally.

I have defined in my application.yml the conditional flag:

service.enable=true

Then I created ServiceMesh.java interface, which should be implemented by serviceA and serviceB as shown below:

public interface ServiceMesh {
}

public class ServiceA implements ServiceMesh {
    // ... code
}

public class ServiceB implements ServiceMesh {
    // ... code
}

I also defined a configuration class:

@Configuration
public class ConditionOnPropertyConfiguration {

@Bean
@ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "true")
public ServiceMesh from(){
    return new ServiceA();
  }

@Bean
@ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "false")
public ServiceMesh from(Environment env){
    return new ServiceB();
  }
}

When running my main class:

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

I got this error:

No qualifying bean of type 'com.example.demo.service.ServiceMesh' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

Expected behavior is to start application

Upvotes: 0

Views: 1788

Answers (1)

Ismail Durmaz
Ismail Durmaz

Reputation: 2621

Change method names from to serviceA and serviceB. I have changed property definition from service.enable=true to service.enabled=true.

    @Bean
    @ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "true")
    public ServiceMesh serviceA() {
        return new ServiceA();
    }

    @Bean
    @ConditionalOnProperty(prefix = "service", name = "enabled", havingValue = "false")
    public ServiceMesh serviceB() {
        return new ServiceB();
    }

Upvotes: 1

Related Questions