3.6.1.1 Eager Initialization of Singletons
Eager initialization of @Singleton
beans maybe desirable in certain scenarios, such as on AWS Lambda where more CPU resources are assigned to Lambda construction than execution.
You can specify whether you want to initialize eagerly @Singleton
scoped beans using the ApplicationContextBuilder interface:
Enabling Eager Initialization of Singletons
public class Application {
public static void main(String[] args) {
Micronaut.build(args)
.eagerInitSingletons(true) (1)
.mainClass(Application.class)
.start();
}
}
1 | Setting eager init to true initializes all singletons |
When you use Micronaut in environments such as Serverless Functions, you will not have an Application class and instead you extend a Micronaut provided class. In those cases, Micronaut provides methods which you can override to enhance the ApplicationContextBuilder
Override of newApplicationContextBuilder()
public class MyFunctionHandler extends MicronautRequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
...
@Nonnull
@Override
protected ApplicationContextBuilder newApplicationContextBuilder() {
ApplicationContextBuilder builder = super.newApplicationContextBuilder();
builder.eagerInitSingletons(true);
return builder;
}
...
}
@ConfigurationReader beans such as @EachProperty or @ConfigurationProperties are singleton beans. If you want to eager init configuration, but keep other @Singleton
scoped beans creation lazy, use eagerInitConfiguration
:
Enabling Eager Initialization of Configuration
public class Application {
public static void main(String[] args) {
Micronaut.build(args)
.eagerInitConfiguration(true) (1)
.mainClass(Application.class)
.start();
}
}
1 | Setting eager init to true initializes all configuration reader beans. |