Injecting Any Bean

If you are not particular about which bean gets injected then you can use the @Any qualifier which will inject the first available bean, for example:

Injecting Any Instance

  1. @Inject @Any
  2. Engine engine;

Injecting Any Instance

  1. @Inject @Any
  2. Engine engine

Injecting Any Instance

  1. @Inject
  2. @field:Any
  3. lateinit var engine: Engine

The @Any qualifier is typically used in conjunction with the BeanProvider interface to allow more dynamic use cases. For example the following Vehicle implementation will start the Engine if the bean is present:

Using BeanProvider with Any

  1. import io.micronaut.context.BeanProvider;
  2. import io.micronaut.context.annotation.Any;
  3. import jakarta.inject.Singleton;
  4. @Singleton
  5. public class Vehicle {
  6. final BeanProvider<Engine> engineProvider;
  7. public Vehicle(@Any BeanProvider<Engine> engineProvider) { (1)
  8. this.engineProvider = engineProvider;
  9. }
  10. void start() {
  11. engineProvider.ifPresent(Engine::start); (2)
  12. }
  13. }

Using BeanProvider with Any

  1. import io.micronaut.context.BeanProvider
  2. import io.micronaut.context.annotation.Any
  3. import jakarta.inject.Singleton
  4. @Singleton
  5. class Vehicle {
  6. final BeanProvider<Engine> engineProvider
  7. Vehicle(@Any BeanProvider<Engine> engineProvider) { (1)
  8. this.engineProvider = engineProvider
  9. }
  10. void start() {
  11. engineProvider.ifPresent(Engine::start) (2)
  12. }
  13. }

Using BeanProvider with Any

  1. import io.micronaut.context.BeanProvider
  2. import io.micronaut.context.annotation.Any
  3. import jakarta.inject.Singleton
  4. @Singleton
  5. class Vehicle(@param:Any val engineProvider: BeanProvider<Engine>) { (1)
  6. fun start() {
  7. engineProvider.ifPresent { it.start() } (2)
  8. }
  9. fun startAll() {
  10. if (engineProvider.isPresent) { (1)
  11. engineProvider.forEach { it.start() } (2)
  12. }
  13. }
1Use @Any to inject the BeanProvider
2Call the start method if the underlying bean is present using the ifPresent method

If there are multiple beans you can also adapt the behaviour. The following example starts all the engines installed in the Vehicle if any are present:

Using BeanProvider with Any

  1. void startAll() {
  2. if (engineProvider.isPresent()) { (1)
  3. engineProvider.stream().forEach(Engine::start); (2)
  4. }
  5. }

Using BeanProvider with Any

  1. void startAll() {
  2. if (engineProvider.isPresent()) { (1)
  3. engineProvider.each {it.start() } (2)
  4. }
  5. }

Using BeanProvider with Any

  1. fun startAll() {
  2. if (engineProvider.isPresent) { (1)
  3. engineProvider.forEach { it.start() } (2)
  4. }
1Check if any beans present
2If so iterate over each one via the stream().forEach(..) method, starting the engines