imgn inject API GitHub

Qualifiers

The problem

A type alone is often not a sufficient address. Two String values โ€” a greeting and a database URL โ€” share a type but must never be confused. Binding by type only would make the second String a duplicate.

How it solves it

A binding key is a type plus an optional qualifier annotation. Qualifier identity is the annotation type and its attribute values: @Named("db") and @Named("cache") are two distinct keys; a marker qualifier with no attributes matches by type alone.

@Named is the built-in string qualifier:

public final class Config {
    @Provides
    @Named("greeting")
    static String greeting() {
        return "Hello";
    }
}

public final class GreetingService {
    @Inject
    public GreetingService(@Named("greeting") String greeting) { ... }
}

Custom qualifiers are ordinary annotations meta-annotated with @QualifyingAnnotation. Attributes participate in identity automatically:

@QualifyingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
public @interface Flavor {
    String value();
}

For programmatic lookups, Key carries the qualifier and Names.named builds the @Named instance:

String greeting = injector.getInstance(Key.of(String.class, Names.named("greeting")));

Limitations