Hi

I tried to give @ConditionalOnMissingBean one of bean method in default config class as a default bean. When there is a customized bean for the same class/interface, the default one won't be initialized. It works as expected when the default and customized bean in the same configuration class(only the one without @ConditionalOnMissingBean will be init), but not for the default config class in other dependency(both of them are init).

I'm not sure whether I'm missing something. I assume that imported configuration class will be using the same context which configuration class import it.

Here is the case. I checked the breakpoints. Both of them are initialized.

// In Spring Boot Application
@Configuration
@Import({BConfig.class})
public class AConfig{
        @Bean public X getX() { return new X(); }
}
// BConfig is in one of maven dependency of Spring Boot Application.
@Configuration
public class BConfig {
        @Bean
        @ConditionalOnMissingBean   // either these three didn't work. All of them are initialized.
//        @ConditionalOnMissingBean(type = "X")    
//        @ConditionalOnMissingBean(value = {X.class})
        public X getDefaultX() { return new X(); }
}

More case: If the customized bean is created by @Component, the default bean in BConfig won't be initialized

Comment From: snicoll

The Javadoc of @ConditionalOnMissingBean explains why that is:

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.

Using this on user configuration is not recommended. And the ordering here is important so the first case works probably by accident more than anything else anyway.

Comment From: BizShuk

I tried @Order as well, but it doesn't work.

Comment From: snicoll

Please review the documentation reference I’ve added. If you have more questions, please ask on stackoverflow.