Spring: Nest Conditions

 20th August 2020 at 2:19pm

Spring 提供了一种各种按条件注入 Bean / Configuration 的机制,如 @ConditionalOnProperty

@Component
@ConditionalOnProperty(value = "test.configname", havingValue = "value1")
public class HarborImageProxy implements IStandardImageProxy {
    // ...
}

当你有多个条件组合时,可以用这几个类:

代码示例可以看各类的 Javadoc。这里举一例:

// Condition 定义
class ConfigNameCondition extends AnyNestedCondition {
    public ConfigNameCondition() {
        super(ConfigurationPhase.PARSE_CONFIGURATION);
    }

    @ConditionalOnProperty(name = "test.configname", value = "value1")
    static class Value1Condition {
    }

    @ConditionalOnProperty(name = "test.configname", value = "value2")
    static class Value2Condition {
    }
}

// Condition 使用
@Bean
@Conditional(ConfigNameCondition.class)
public SomeBean someBean() {
    return new SomeBean();
}