何时使用Spring @ConfigurationCondition vs. @Condition? [英] When to use Spring @ConfigurationCondition vs. @Condition?
问题描述
Spring 4有两个新的注释 @Condition
和 @ConfigurationConditon
用于控制是否将bean添加到弹簧中应用背景。 JavaDoc没有提供足够的上下文/大图来理解 @ConfigurationCondition
的用例。
Spring 4 has two new annotations @Condition
and @ConfigurationConditon
for controlling whether a bean is added to the spring application context. The JavaDoc does not provide enough context / big picture to understand the use cases for @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
类。
普通条件
对99%的用例都很好,所以你应该先考虑一下。专业化实际上是关于确定 @Configuration
类处理的阶段应评估条件。
Plain Condition
is just fine for 99% of your use cases so you should consider that first. The specialization is really about determining in which phase of the processing of @Configuration
classes the condition should be evaluated.
分为两个阶段:
-
PARSE_CONFIGURATION
评估解析@Configuration
-annotated类时的条件。这样就有机会完全排除配置类 -
REGISTER_BEAN
在注册配置类中的bean时评估条件。这不会阻止添加配置类,但如果条件不匹配,则允许跳过bean定义(由匹配
定义条件
接口)
PARSE_CONFIGURATION
evaluates the condition when the@Configuration
-annotated class is parsed. This gives a chance to fully exclude the configuration classREGISTER_BEAN
evaluates the condition when a bean from a configuration class is registered. This does not prevent the configuration class to be added but it allows to skip a bean definition if the condition does not match (as defined by thematches
method of theCondition
interface)
Spring Boot有一个 OnBeanCondition
在注册阶段基本上检查是否存在另一个bean。这是 ConditionalOnBean
的核心,当bean存在时基本上会做某事
Spring Boot has a OnBeanCondition
that basically checks during the registration phase if another bean is present. This is the core of ConditionalOnBean
that basically does something when a bean is present
这篇关于何时使用Spring @ConfigurationCondition vs. @Condition?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!