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
@Inject @Any
Engine engine;
Injecting Any Instance
@Inject @Any
Engine engine
Injecting Any Instance
@Inject
@field:Any
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
import io.micronaut.context.BeanProvider;
import io.micronaut.context.annotation.Any;
import jakarta.inject.Singleton;
@Singleton
public class Vehicle {
final BeanProvider<Engine> engineProvider;
public Vehicle(@Any BeanProvider<Engine> engineProvider) { (1)
this.engineProvider = engineProvider;
}
void start() {
engineProvider.ifPresent(Engine::start); (2)
}
}
Using BeanProvider with Any
import io.micronaut.context.BeanProvider
import io.micronaut.context.annotation.Any
import jakarta.inject.Singleton
@Singleton
class Vehicle {
final BeanProvider<Engine> engineProvider
Vehicle(@Any BeanProvider<Engine> engineProvider) { (1)
this.engineProvider = engineProvider
}
void start() {
engineProvider.ifPresent(Engine::start) (2)
}
}
Using BeanProvider with Any
import io.micronaut.context.BeanProvider
import io.micronaut.context.annotation.Any
import jakarta.inject.Singleton
@Singleton
class Vehicle(@param:Any val engineProvider: BeanProvider<Engine>) { (1)
fun start() {
engineProvider.ifPresent { it.start() } (2)
}
fun startAll() {
if (engineProvider.isPresent) { (1)
engineProvider.forEach { it.start() } (2)
}
}
1 | Use @Any to inject the BeanProvider |
2 | Call 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
void startAll() {
if (engineProvider.isPresent()) { (1)
engineProvider.stream().forEach(Engine::start); (2)
}
}
Using BeanProvider with Any
void startAll() {
if (engineProvider.isPresent()) { (1)
engineProvider.each {it.start() } (2)
}
}
Using BeanProvider with Any
fun startAll() {
if (engineProvider.isPresent) { (1)
engineProvider.forEach { it.start() } (2)
}
1 | Check if any beans present |
2 | If so iterate over each one via the stream().forEach(..) method, starting the engines |