Spring 提供了一种各种按条件注入 Bean / Configuration 的机制,如 @ConditionalOnProperty
:
@Component
@ConditionalOnProperty(value = "test.configname", havingValue = "value1")
public class HarborImageProxy implements IStandardImageProxy {
// ...
}
当你有多个条件组合时,可以用这几个类:
- AllNestedConditions:当多个条件同时成立
- AnyNestedCondition:当多个条件任一成立
- NoneNestedConditions:当多个条件都不成立
代码示例可以看各类的 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();
}