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 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() will create a new instance. |
Collection Ordering
When injecting a collection of beans, they will not be ordered by default. To allow for the beans to be ordered, implement the Ordered interface. If the requested bean type does not implement Ordered, then the @Order annotation will be searched for on any 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 javax.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 javax.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 javax.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 will be returned in ascending order based on the value supplied in the annotation.