Condition class abstract interface

A rule that decides whether a bean is registered at all.

Use one when a bean should exist only in some situations that a profile does not describe: a property set, a file present, another bean missing. The rule runs while the modules load, before any bean is created; when it does not match, the bean is not registered, as if it had no annotation. Spring Boot's @ConditionalOn... annotations are conditions of this kind.

Write a class that implements it, then use it in one of two ways: through @Conditional([MyCondition]) (the class needs a no-argument constructor), or as an annotation itself. Any const annotation class that implements Condition is evaluated, so conditions with arguments, such as @ConditionalOnProperty('feature.enabled'), are plain classes.

// The audit feature exists only with `feature.audit=true`.
class ConditionalOnProperty implements Condition {
  const ConditionalOnProperty(this.name, {this.havingValue = 'true'});

  final String name;
  final String havingValue;

  @override
  bool matches(ConditionContext context) =>
      context.environment.getProperty(name) == havingValue;
}

@Component()
@ConditionalOnProperty('feature.audit')
class AuditFeature {}

Spring (Java):

class OnAuditEnabled implements Condition {
  public boolean matches(ConditionContext ctx, AnnotatedTypeMetadata m) {
    return "true".equals(
        ctx.getEnvironment().getProperty("feature.audit"));
  }
}

@Component
@Conditional(OnAuditEnabled.class)
class AuditFeature {}

Unlike Spring there is no AnnotatedTypeMetadata parameter: an annotation-style condition reads its own fields instead.

Properties

hashCode → int
The hash code for this object.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

matches(ConditionContext context) → bool
Whether the annotated bean should be registered; context gives access to the configuration and the definitions registered so far.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited