3.4 Injectable Container Types
In addition to being able to inject beans, Micronaut natively supports injecting the following types:
Type | Description | Example |
---|---|---|
An |
| |
An |
| |
A lazy |
| |
A native array of beans of a given type |
| |
A |
| |
A |
| |
A |
|
There are 3 different provider types supported, however the BeanProvider is the one we suggest to use. |
When injecting a
In this example, the injected member variable |
A prototype bean will have one instance created per place the bean is injected. When a prototype bean is injected as a provider, each call to get() creates a new instance. |
Collection Ordering
When injecting a collection of beans, they are not ordered by default. Implement the Ordered interface to inject an ordered collection. If the requested bean type does not implement Ordered, Micronaut searches for the @Order annotation on beans.
The @Order annotation is especially useful for ordering beans created by factories where the bean type is a class in a third-party library. In this example, both LowRateLimit
and HighRateLimit
implement the RateLimit
interface.
Factory with @Order
import io.micronaut.context.annotation.Factory;
import io.micronaut.core.annotation.Order;
import jakarta.inject.Singleton;
import java.time.Duration;
@Factory
public class RateLimitsFactory {
@Singleton
@Order(20)
LowRateLimit rateLimit2() {
return new LowRateLimit(Duration.ofMinutes(50), 100);
}
@Singleton
@Order(10)
HighRateLimit rateLimit1() {
return new HighRateLimit(Duration.ofMinutes(50), 1000);
}
}
Factory with @Order
import io.micronaut.context.annotation.Factory
import io.micronaut.core.annotation.Order
import jakarta.inject.Singleton
import java.time.Duration
@Factory
class RateLimitsFactory {
@Singleton
@Order(20)
LowRateLimit rateLimit2() {
new LowRateLimit(Duration.ofMinutes(50), 100);
}
@Singleton
@Order(10)
HighRateLimit rateLimit1() {
new HighRateLimit(Duration.ofMinutes(50), 1000);
}
}
Factory with @Order
import io.micronaut.context.annotation.Factory
import io.micronaut.core.annotation.Order
import java.time.Duration
import jakarta.inject.Singleton
@Factory
class RateLimitsFactory {
@Singleton
@Order(20)
fun rateLimit2(): LowRateLimit {
return LowRateLimit(Duration.ofMinutes(50), 100)
}
@Singleton
@Order(10)
fun rateLimit1(): HighRateLimit {
return HighRateLimit(Duration.ofMinutes(50), 1000)
}
}
When a collection of RateLimit
beans are requested from the context, they are returned in ascending order based on the value in the annotation.
Injecting a Bean by Order
When injecting a single instance of a bean the @Order annotation can also be used to define which bean has the highest precedence and hence should be injected.
The Ordered interface is not taken into account when selecting a single instance as this would require instantiating the bean to resolve the order. |