这是我对在 Spring 自动配置中使用自定义条件的问题的看法。有点类似于 @Strumbels 提出的建议,但更可重用。
@Conditional 注释在应用程序启动的早期执行。属性源已加载,但尚未创建 ConfgurationProperties bean。但是,我们可以通过自己将属性绑定到 Java POJO 来解决这个问题。
首先我介绍一个函数式接口,它使我们能够定义任何自定义逻辑来检查属性是否确实存在。在您的情况下,此方法将负责检查属性 List 是否为空/null,以及其中的所有项目是否有效。
public interface OptionalProperties {
boolean isPresent();
}
现在让我们创建一个注释,它将使用 Spring @Conditional 进行元注释,并允许我们定义自定义参数。 prefix 代表属性命名空间,targetClass 代表属性应该映射到的配置属性模型类。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnConfigurationPropertiesCondition.class)
public @interface ConditionalOnConfigurationProperties {
String prefix();
Class<? extends OptionalProperties> targetClass();
}
现在是主要部分。自定义条件实现。
public class OnConfigurationPropertiesCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
MergedAnnotation<ConditionalOnConfigurationProperties> mergedAnnotation = metadata.getAnnotations().get(ConditionalOnConfigurationProperties.class);
String prefix = mergedAnnotation.getString("prefix");
Class<?> targetClass = mergedAnnotation.getClass("targetClass");
// type precondition
if (!OptionalProperties.class.isAssignableFrom(targetClass)) {
return ConditionOutcome.noMatch("Target type does not implement the OptionalProperties interface.");
}
// the crux of this solution, binding properties to Java POJO
Object bean = Binder.get(context.getEnvironment()).bind(prefix, targetClass).orElse(null);
// if properties are not present at all return no match
if (bean == null) {
return ConditionOutcome.noMatch("Binding properties to target type resulted in null value.");
}
OptionalProperties props = (OptionalProperties) bean;
// execute method from OptionalProperties interface
// to check if condition should be matched or not
// can include any custom logic using property values in a type safe manner
if (props.isPresent()) {
return ConditionOutcome.match();
} else {
return ConditionOutcome.noMatch("Properties are not present.");
}
}
}
现在您应该创建自己的配置属性类来实现OptionalProperties 接口。
@ConfigurationProperties("your.property.prefix")
@ConstructorBinding
public class YourConfigurationProperties implements OptionalProperties {
// Service is your POJO representing the name and version subproperties
private final List<Service> services;
@Override
public boolean isPresent() {
return services != null && services.stream().all(Service::isValid);
}
}
然后在 Spring @Configuration 上课。
@Configuration
@ConditionalOnConfigurationProperties(prefix = "", targetClass = YourConfigurationProperties.class)
class AutoConfigureServices {
....
}
此解决方案有两个缺点:
- 必须在两个位置指定属性前缀:
@ConfigurationProperties 注释和@ConditionalOnConfigurationProperties 注释。这可以通过在配置属性 POJO 中定义 public static final String PREFIX = "namespace" 来部分缓解。
- 属性绑定过程在每次使用我们的自定义条件注释时单独执行,然后再次创建配置属性 bean 本身。它仅在应用启动期间发生,因此应该不是问题,但仍然是一种低效率。