Spring Configuration Tricks

Nov 16, 2021 | - views

Aggregate Conditions

You can use AllNestedConditions when you want to aggregate multiple conditions.

import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

class AggregatedConditionCondition extends AllNestedConditions {
  public AggregatedConditionCondition() {
    super(ConfigurationPhase.PARSE_CONFIGURATION);
  }

  @ConditionalOnProperty(value = "property1", havingValue = "value1")
  static class IsCond1 {
    // empty
  }

  @ConditionalOnProperty(value = "property2", havingValue = "value2")
  static class IsCond2 {
    // empty
  }
}

Custom condition (like is it falsy)

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import lombok.NonNull;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.type.AnnotatedTypeMetadata;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(ConditionalOnFalsyPropertyInner.class)
@interface ConditionalOnFalsyProperty {
  String value();
}

class ConditionalOnFalsyPropertyInner implements Condition {
  @Override
  public boolean matches(@NonNull ConditionContext context, AnnotatedTypeMetadata metadata) {
    var attrs =
        metadata.getAnnotationAttributes(
            ai.conundrum.connectors.condition.ConditionalOnFalsyProperty.class.getName());
    if (attrs == null || !attrs.containsKey("value")) {
      return true;
    }

    String propertyName = (String) attrs.get("value");
    String value = context.getEnvironment().getProperty(propertyName);
    if (value == null) {
      throw new RuntimeException(String.format("Property '%s' not exists", propertyName));
    }

    return value.isBlank() || "false".equals(value);
  }
}