Prerequisites

  • Two beans exist in the project: MainBean and DependencyBean;
  • MainBean is annotated with a stereotype, but DependencyBean is not, instead it is defined in AutoConfiguration;
  • DependencyBean has no dependencies, thus can be easily created, but MainBean depends on the existence of DependencyBean;

Expected Result

If DependencyBean has no dependencies, it should be created. MainBean has a dependency on DependencyBean, but since DependencyBean will be created, then MainBean should also be created.

Actual Result

Only DependencyBean created.

Reproducer

https://github.com/alexey-anufriev/spring-autoconfiguration-demo

Comment From: philwebb

Your MainBean class is being picked up by component scanning and isn't an auto-configuration bean so @ConditionalOnBean cannot be used on it. From the @ConditionalOnBean javadoc:

The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.

Basically, @ConditionalOnBean should only be used on auto-configuration classes and furthermore those classes should use before and after attributes to ensure they're ordered correctly.

Comment From: alexey-anufriev

@philwebb, thank you for explanation.

Shouldn't there be a validation + warning in case if bean's graph has this type of interconnections that are not predictable?

Comment From: philwebb

@alexey-anufriev That would be nice, unfortunately we've not found an easy way to detect such problems.