
此处不讨论实际Bean确实存在/不存在及存在多个的问题,仅讨论一种看似符合条件但按预期加载的情况。
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ RequestInterceptor.class, HttpServletRequest.class })
@ConditionalOnMissingBean(BdapRequestInterceptor.class)
@Slf4j
public class BdapRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// do something
}
}此处调整主要用于观察bean加载过程,确认bean加载/不加载的的条件判断情况:
#以logback为例
logging:
level:
org: debug··· BdapRequestInterceptor: Did not match: - @ConditionalOnMissingBean (types: com.pactera.bi.app.config.BdapRequestInterceptor; SearchStrategy: all) found beans of type ‘com.pactera.bi.app.config.BdapRequestInterceptor’ bdapRequestInterceptor (OnBeanCondition) Matched: - @ConditionalOnClass found required classes ‘feign.RequestInterceptor’, ‘javax.servlet.http.HttpServletRequest’ (OnClassCondition) - @ConditionalOnWebApplication (required) found ‘session’ scope (OnWebApplicationCondition) ···


那么,由于配置类解析顺序的不同,ConditionalOnMissingBean/ConditionalOnBean在作用不同的Bean及BeanDefinition上时,所产生的效果也并不同。
You need to be very careful about the order in which bean definitions are added, as these conditions are evaluated based on what has been processed so far. For this reason, we recommend using only @ConditionalOnBean and @ConditionalOnMissingBean annotations on auto-configuration classes (since these are guaranteed to load after any user-defined bean definitions have been added) @ConditionalOnBean and @ConditionalOnMissingBean do not prevent @Configuration classes from being created. The only difference between using these conditions at the class level and marking each contained @Bean method with the annotation is that the former prevents registration of the @Configuration class as a bean if the condition does not match

首先官方的建议是在自动配置种才建议使用ConditionalOnMissingBean/ConditionalOnBean注解,其次提醒了加载顺序的问题。 关于自动配置(此处仅引用,更为详细的建议自行查询官方资料):
