@ConditionalOnProperty用于列表或数组?
我正在使用Spring Boot 1.4.3 @AutoConfiguration
,根据用户指定的属性自动创建bean。用户可以指定一系列服务,其中
和 为必填字段:
service[0].name=myServiceAservice[0].version=1.0
service[1].name=myServiceB
service[1].version=1.2
...
如果用户忘记了甚至只在一项服务上都指定了必填字段,那么我想回退而不创建任何bean。我可以用@ConditionalOnProperty
吗?我想要类似的东西:
@Configuration@ConditionalOnProperty({"service[i].name", "service[i].version"})
class AutoConfigureServices {
....
}
回答:
这是Condition
我创建的风俗。它需要一些修饰才能更通用(即,不对字符串进行硬编码),但对我来说效果很好。
要使用,我用以下注释了我的Configuration类
@Conditional(RequiredRepeatablePropertiesCondition.class)
public class RequiredRepeatablePropertiesCondition extends SpringBootCondition { private static final Logger LOGGER = LoggerFactory.getLogger(RequiredRepeatablePropertiesCondition.class.getName());
public static final String[] REQUIRED_KEYS = {
"my.services[i].version",
"my.services[i].name"
};
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
List<String> missingProperties = new ArrayList<>();
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment());
Map<String, Object> services = resolver.getSubProperties("my.services");
if (services.size() == 0) {
missingProperties.addAll(Arrays.asList(REQUIRED_KEYS));
return getConditionOutcome(missingProperties);
}
//gather indexes to check: [0], [1], [3], etc
Pattern p = Pattern.compile("\\[(\\d+)\\]");
Set<String> uniqueIndexes = new HashSet<String>();
for (String key : services.keySet()) {
Matcher m = p.matcher(key);
if (m.find()) {
uniqueIndexes.add(m.group(1));
}
}
//loop each index and check required props
uniqueIndexes.forEach(index -> {
for (String genericKey : REQUIRED_KEYS) {
String multiServiceKey = genericKey.replace("[i]", "[" + index + "]");
if (!resolver.containsProperty(multiServiceKey)) {
missingProperties.add(multiServiceKey);
}
}
});
return getConditionOutcome(missingProperties);
}
private ConditionOutcome getConditionOutcome(List<String> missingProperties) {
if (missingProperties.isEmpty()) {
return ConditionOutcome.match(ConditionMessage.forCondition(RequiredRepeatablePropertiesCondition.class.getCanonicalName())
.found("property", "properties")
.items(Arrays.asList(REQUIRED_KEYS)));
}
return ConditionOutcome.noMatch(
ConditionMessage.forCondition(RequiredRepeatablePropertiesCondition.class.getCanonicalName())
.didNotFind("property", "properties")
.items(missingProperties)
);
}
}
以上是 @ConditionalOnProperty用于列表或数组? 的全部内容, 来源链接: utcz.com/qa/419866.html