0

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.

Jerald Baker
  • 1,121
  • 1
  • 12
  • 48

1 Answers1

1

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
   }
}
Alexandru Somai
  • 1,395
  • 1
  • 7
  • 16
  • DependsOn will force the creation of ExampleServices even though the property condition it depends on evaluates to false – Jerald Baker Feb 28 '20 at 09:39