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

ams*_*ams 5 java spring

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.
         *
         * <p>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.
         *
         * <p>At the time that the condition is evaluated all {@code @Configuration}s
         * will have been parsed.
         */
        REGISTER_BEAN
    }

}
Run Code Online (Sandbox Code Playgroud)

Ste*_*oll 6

ConfigurationCondition是一个专业化Condition@Configuration课程.

Condition对99%的用例来说,普通版都没问题,所以你应该先考虑一下.专业化实际上是关于确定应该评估条件的类处理的哪个阶段@Configuration.

有两个阶段:

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

Spring Boot OnBeanCondition在注册阶段基本上会检查是否存在另一个bean.这是ConditionalOnBeanbean存在时基本上做的事情的核心