3

I have a java @Configuration class with a FOO @Bean annotated with @ConditionalOnBean(BAR.class). As I expect this bean to be or not provided by the importer project, it's not present anywhere in my project.

In my integration test, I mock Bar.class by means of @MockBeans. But for some reason Spring-Boot -debug tells me it did not found it so my conditional bean has not been loaded.

I'm almost sure this situation has worked properly in the past, but did I configure anything extra? I can't manage to make it work

P.S> I discovered that manually re-registering the @Bean in the same @Configuration as the conditional does not see it neither! Is there any known bug related to his?

Autoreply: The culprit in this case is

You need to be very careful about the order that bean definitions are added as these conditions are evaluated based on what has been processed so far. For this reason, we recommend only using @ConditionalOnBean and @ConditionalOnMissingBean annotations on auto-configuration classes (since these are guaranteed to load after any user-defined beans definitions have been added).

P.S2> I realized Bar.class is an interface but I don't see why shouldn't it work as long as an implementation is present

P.S3> I found out that the MockitoTestExecutionListener is executed after the OnBeanCondition class. This seems my problem totally.

Whimusical
  • 6,401
  • 11
  • 62
  • 105
  • It is not clear, could you please clarify "As I expect this bean to be or not provided by the importer project, it's not present anywhere in my project." – fg78nc Jul 10 '17 at 18:37
  • @fg78nc I'm doing an starter (hence the `@ConditionalOnBean`), so depending on the presence or not of BAR @Bean, I'll configure FOO or not. In the context of Boot, is there any name for what I am calling "importer"? – Whimusical Jul 10 '17 at 18:44
  • Regardless of whether they are *currently* supposed to, it makes complete sense to me that if I provide an `@MockBean` in my test, it should trigger autoconfiguration conditions. I suggest filing a bug against BOOT describing this case. – chrylis -cautiouslyoptimistic- Jul 10 '17 at 18:48
  • I extended the question with 2 considerations – Whimusical Jul 10 '17 at 18:56
  • Is `@ConditionalOnBean` in an auto configuration class? – Abhijit Sarkar Jul 10 '17 at 19:50
  • its intended to be, currently is just a plain configuration – Whimusical Jul 10 '17 at 19:57
  • "As I expect this bean to be or not provided by the importer project, it's not present anywhere in my project." That's actually wrong. Please review the javadoc of `@ConditionalOnBean`. It's only meant to be used in auto-configuration. – Stephane Nicoll Jul 11 '17 at 18:06
  • I pasted the responses from Github you gave me and Ill close the question – Whimusical Jul 11 '17 at 18:15

1 Answers1

2

This and this explain why it is not possible:

Whimusical
  • 6,401
  • 11
  • 62
  • 105