java - 何时使用 Spring @ConfigurationCondition 与 @Condition?

标签 java spring

Spring 4 有两个新的注解@Condition@ConfigurationConditon 用于控制一个bean 是否被添加到spring application context 中。 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
    }

}

最佳答案

ConfigurationCondition@Configuration 类的 Condition 的特化。

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

有两个阶段:

  • PARSE_CONFIGURATION 评估解析 @Configuration 注释类时的条件。这给了一个完全排除配置类的机会
  • REGISTER_BEAN 评估来自配置类的 bean 注册时的条件。这不会阻止添加配置类,但它允许在条件不匹配时跳过 bean 定义(由 Condition 接口(interface)的 matches 方法定义)

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

关于java - 何时使用 Spring @ConfigurationCondition 与 @Condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23299273/

相关文章:

java - 多个通知,同时以一天的间隔重复它们。在通知功能中使用唯一 ID,但无法获得所需的输出

java - 使用 Spring Boot、JPA 通过引用关联实体

Spring 数据 JPA。如何从 findAll() 方法中仅获取 ID 列表

java - 如何创建一个监听状态变化的线程?

java - 我需要列出使用 java.lang.ApplicationShutdownHooks 注册的钩子(Hook)

java - 如果 ExecutorService 的队列已满会发生什么

spring - Autowiring 到 JPA 转换器

java - SpringBoot : How to call a API chain using reactive programming?

java - ManyToMany Hibernate保存相关对象

java - 尝试连接到 Docker Postgres DB 时没有合适的 JDBC 驱动程序