何时使用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
可以指定Condition
或ConfigurationCondition
。
@Conditional
根据@Conditional
确定是启用还是禁用@Configuration
类。 正如文档所说 ,最好的例子是@Profile
注释本身,它根据所选的配置文件确定加载或未加载的bean。
ConfigurationCondition
考虑的两个阶段是@Configuration
类经历的阶段:首先解析类,然后注册和创建bean。