3.7.3 Scopes on Meta Annotations

Scopes can be defined on meta annotations that you can then apply to your classes. Consider the following example meta annotation:

  1. import io.micronaut.context.annotation.Requires;
  2. import jakarta.inject.Singleton;
  3. import java.lang.annotation.Documented;
  4. import java.lang.annotation.Retention;
  5. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  6. @Requires(classes = Car.class) (1)
  7. @Singleton (2)
  8. @Documented
  9. @Retention(RUNTIME)
  10. public @interface Driver {
  11. }
  1. import io.micronaut.context.annotation.Requires
  2. import jakarta.inject.Singleton
  3. import java.lang.annotation.Documented
  4. import java.lang.annotation.Retention
  5. import static java.lang.annotation.RetentionPolicy.RUNTIME
  6. @Requires(classes = Car.class) (1)
  7. @Singleton (2)
  8. @Documented
  9. @Retention(RUNTIME)
  10. @interface Driver {
  11. }
  1. import io.micronaut.context.annotation.Requires
  2. import jakarta.inject.Singleton
  3. import kotlin.annotation.AnnotationRetention.RUNTIME
  4. @Requires(classes = [Car::class]) (1)
  5. @Singleton (2)
  6. @MustBeDocumented
  7. @Retention(RUNTIME)
  8. annotation class Driver
1The scope declares a requirement on a Car class using Requires
2The annotation is declared as @Singleton

In the example above the @Singleton annotation is applied to the @Driver annotation which results in every class that is annotated with @Driver being regarded as singleton.

Note that in this case it is not possible to alter the scope when the annotation is applied. For example, the following will not override the scope declared by @Driver and is invalid:

Declaring Another Scope

  1. @Driver
  2. @Prototype
  3. class Foo {}

For the scope to be overridable, instead use the DefaultScope annotation on @Driver which allows a default scope to be specified if none other is present:

Using @DefaultScope

  1. @Requires(classes = Car.class)
  2. @DefaultScope(Singleton.class) (1)
  3. @Documented
  4. @Retention(RUNTIME)
  5. public @interface Driver {
  6. }
  1. @Requires(classes = Car.class)
  2. @DefaultScope(Singleton.class) (1)
  3. @Documented
  4. @Retention(RUNTIME)
  5. @interface Driver {
  6. }
  1. @Requires(classes = [Car::class])
  2. @DefaultScope(Singleton::class) (1)
  3. @Documented
  4. @Retention(RUNTIME)
  5. annotation class Driver
1DefaultScope declares the scope to use if none is specified