Jerald Baker
Jerald Baker

Reputation: 1369

@ConditionalOnBean not detecting bean even though it is created

I have a class annotated with @Configuration and a bean

  @Configuration
  public class ExampleServiceConfig {

  @Bean
  @ConditionalOnProperty(value = servicefeature1.enable", havingValue = "true")
  public ExampleServices exampleServices() {
    return new ExampleServices();

  }

I then have another service class that depends on the bean above:

@ConditionalOnBean(ExampleServices.class)
public class AnotherService{

   @Autowired
   public AnotherService(ExampleServices exampleServices){
      this.exampleServices = exampleServices
   }
}

In the spring debug logs, I see the first bean is getting created:

2020-02-28 14:08:51.841 DEBUG 18158 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Creating shared instance of singleton bean 'exampleServices'

But the AnotherService() is not getting created:

AnotherService:
      Did not match:
         - @ConditionalOnBean (types: x.x.x.ExampleServices; SearchStrategy: all) did not find any beans of type x.x.x.ExampleServices (OnBeanCondition)

Why is the AnotherService() not getting created even though the ExampleService bean was created successfully?

Also, I see the "did not match" log after the ExampleService bean got created.

Upvotes: 0

Views: 3537

Answers (1)

Alexandru Somai
Alexandru Somai

Reputation: 1405

I think adding @DependsOn to the mix could fix your issue. Here is another answer, somewhat similar with your problem: https://stackoverflow.com/a/50518946/6908551

@Component
@ConditionalOnBean(ExampleServices.class)
@DependsOn("exampleServices")
public class AnotherService {

   @Autowired
   public AnotherService(ExampleServices exampleServices) {
      this.exampleServices = exampleServices
   }
}

Upvotes: 1

Related Questions