看起来@ConditionalOnProperty没有多值属性。
在Spring环境中,它们呈现为:
prop[0]=a
prop[1]=b
我的解决方案是创建一个自己的 @Conditional 扩展,可以处理多个属性值。以下是示例。
注释:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty2 {
String name();
String value();
}
条件:
class OnPropertyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String name = attribute(metadata, "name");
String value = attribute(metadata, "value");
String searchName = name;
String property = property(context, searchName);
int i = 0;
do {
if (value.equals(property)) return true;
searchName = name + '[' + i++ + ']';
} while ((property = property(context, searchName)) != null);
return false;
}
private String attribute(AnnotatedTypeMetadata metadata, String name) {
return (String) metadata.getAnnotationAttributes(ConditionalOnProperty2.class.getName()).get(name);
}
private String property(ConditionContext context, String name) {
return context.getEnvironment().getProperty(name);
}
}
使用方法:
@Bean
@ConditionalOnProperty2(name = "prop", havingValue = "a")
public SomeBean bean1() {
return new SomeBean1();
}
@Bean
@ConditionalOnProperty2(name = "prop", havingValue = "b")
public SomeBean bean2() {
return new SomeBean2();
}