imgn inject API GitHub

Conditional Beans

The problem

Some beans should exist only in some deployments โ€” a feature behind a flag, an integration only configured environments use. Without support for this, the choice is between shipping separate artifacts per environment or writing wiring code that consults configuration by hand.

How it solves it

A bean or @Provides method can carry a conditioning annotation. When the injector is created, each factory's conditions are evaluated; an unmatched condition removes the bean from the graph entirely โ€” no binding, no bean definition, no collection contribution.

@ConditionalOnProperty is built in:

@ConditionalOnProperty(value = "examples.premium", havingValue = "true")
public final class PremiumFeature {
    @Inject
    public PremiumFeature() {}
}
// property unset: the bean does not exist
Injector.create().getBeanDefinition(Key.of(PremiumFeature.class)); // Optional.empty()

System.setProperty("examples.premium", "true");
Injector.create().getInstance(PremiumFeature.class); // resolves

Its attributes: value names the property, havingValue is the required value (empty means "any value"), and matchIfMissing makes an absent property count as a match. Properties are read from system properties.

Custom conditions

A condition is a pair, mirroring how scopes work: an annotation meta-annotated with @ConditioningAnnotation, and a Condition implementation discovered through ServiceLoader. The condition receives the annotation's attribute values and decides matches.

Limitations