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

  1. public class Application {
  2. public static void main(String[] args) {
  3. Micronaut.build(args)
  4. .eagerInitSingletons(true) (1)
  5. .mainClass(Application.class)
  6. .start();
  7. }
  8. }
1Setting 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()

  1. public class MyFunctionHandler extends MicronautRequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
  2. ...
  3. @Nonnull
  4. @Override
  5. protected ApplicationContextBuilder newApplicationContextBuilder() {
  6. ApplicationContextBuilder builder = super.newApplicationContextBuilder();
  7. builder.eagerInitSingletons(true);
  8. return builder;
  9. }
  10. ...
  11. }

@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

  1. public class Application {
  2. public static void main(String[] args) {
  3. Micronaut.build(args)
  4. .eagerInitConfiguration(true) (1)
  5. .mainClass(Application.class)
  6. .start();
  7. }
  8. }
1Setting eager init to true initializes all configuration reader beans.