何时使用Spring @ConfigurationCondition vs. @Condition?

Spring 4有两个新的注释@Condition@ConfigurationConditon用于控制是否将bean添加到spring应用程序上下文中。 JavaDoc没有提供足够的上下文/大图来理解@ConfigurationCondition的用例。

应该何时使用@ConfigurationCondition@Condition

 public interface ConfigurationCondition extends Condition { /** * Returns the {@link ConfigurationPhase} in which the condition should be evaluated. */ ConfigurationPhase getConfigurationPhase(); /** * The various configuration phases where the condition could be evaluated. */ public static enum ConfigurationPhase { /** * The {@link Condition} should be evaluated as a {@code @Configuration} class is * being parsed. * * 

If the condition does not match at this point the {@code @Configuration} * class will not be added. */ PARSE_CONFIGURATION, /** * The {@link Condition} should be evaluated when adding a regular (non * {@code @Configuration}) bean. The condition will not prevent * {@code @Configuration} classes from being added. * *

At the time that the condition is evaluated all {@code @Configuration}s * will have been parsed. */ REGISTER_BEAN } }

ConfigurationCondition@Configuration类的Condition的特化。

普通Condition适用于99%的用例,因此您应该首先考虑这一点。 专业化实际上是关于确定应该评估条件的@Configuration类的处理阶段

有两个阶段:

  • PARSE_CONFIGURATION在解析@Configuration -annotated类时评估条件。 这样就有机会完全排除配置类
  • REGISTER_BEAN在注册配置类中的bean时评估条件。 这不会阻止添加配置类,但如果条件不匹配(由Condition接口的matches方法定义),它允许跳过bean定义

Spring Boot有一个OnBeanCondition ,它在注册阶段基本上检查是否存在另一个bean。 这是ConditionalOnBean的核心,它基本上在bean存在时执行某些操作

没有@ConfigurationCondition@Condition注释,但@Conditional 。 对于@Conditional可以指定ConditionConfigurationCondition

@Conditional根据@Conditional确定是启用还是禁用@Configuration类。 正如文档所说 ,最好的例子是@Profile注释本身,它根据所选的配置文件确定加载或未加载的bean。

ConfigurationCondition考虑的两个阶段是@Configuration类经历的阶段:首先解析类,然后注册和创建bean。