@ConditionalOnProperty 用于多值属性 [英] @ConditionalOnProperty for multi-valued properies
问题描述
有没有办法使用基于多值属性的@ConditionalOnProperty注解?
Is there any way to use @ConditionalOnProperty annotation based on multi-valued property?
弹簧配置:
@Bean
@ConditionalOnProperty(name = "prop", havingValue = "a")
public SomeBean bean1() {
return new SomeBean1();
}
@Bean
@ConditionalOnProperty(name = "prop", havingValue = "b")
public SomeBean bean2() {
return new SomeBean2();
}
和 application.yaml
and application.yaml
prop:
- a
- b
我希望 bean: bean1 和 bean2 都将在 spring 上下文中注册,但它们中的任何一个都没有注册.有什么办法吗?
I expect that both beans: bean1 and bean2 will be registered in the spring context, but no one from them isn't registered. Is there any way to do it?
推荐答案
看起来@ConditionalOnProperty 没有多值属性.在 spring 环境中,它们呈现为
It looks like @ConditionalOnProperty haven't multivalued properies. In spring environment they are presented as
prop[0]=a
prop[1]=b
我的解决方案是制作我自己的@Conditional 扩展,它能够处理多值属性.这是示例.
My solution is to make my own @Conditional extension, that is able to work with multivalued properies. Here is the example.
注释:
@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();
}
这篇关于@ConditionalOnProperty 用于多值属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!