Qualifying By Annotation

In addition to being able to qualify by name, you can build your own qualifiers using the Qualifier annotation. For example, consider the following annotation:

  1. import javax.inject.Qualifier;
  2. import java.lang.annotation.Retention;
  3. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  4. @Qualifier
  5. @Retention(RUNTIME)
  6. public @interface V8 {
  7. }
  1. import javax.inject.Qualifier
  2. import java.lang.annotation.Retention
  3. import static java.lang.annotation.RetentionPolicy.RUNTIME
  4. @Qualifier
  5. @Retention(RUNTIME)
  6. @interface V8 {
  7. }
  1. import javax.inject.Qualifier
  2. import java.lang.annotation.Retention
  3. import java.lang.annotation.RetentionPolicy.RUNTIME
  4. @Qualifier
  5. @Retention(RUNTIME)
  6. annotation class V8

The above annotation is itself annotated with the @Qualifier annotation to designate it as a qualifier. You can then use the annotation at any injection point in your code. For example:

  1. @Inject Vehicle(@V8 Engine engine) {
  2. this.engine = engine;
  3. }
  1. @Inject Vehicle(@V8 Engine engine) {
  2. this.engine = engine
  3. }
  1. @Inject constructor(@V8 val engine: Engine) {