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/