3.6.1 Built-In Scopes

Table 1. Micronaut Built-in Scopes
TypeDescription

@Singleton

Singleton scope indicates only one instance of the bean should exist

@Context

Context scope indicates that the bean should be created at the same time as the ApplicationContext (eager initialization)

@Prototype

Prototype scope indicates that a new instance of the bean is created each time it is injected

@Infrastructure

Infrastructure scope represents a bean that cannot be overridden or replaced using @Replaces because it is critical to the functioning of the system.

@ThreadLocal

@ThreadLocal scope is a custom scope that associates a bean per thread via a ThreadLocal

@Refreshable

@Refreshable scope is a custom scope that allows a bean’s state to be refreshed via the /refresh endpoint.

@RequestScope

@RequestScope scope is a custom scope that indicates a new instance of the bean is created and associated with each HTTP request

The @Prototype annotation is a synonym for @Bean because the default scope is prototype.

Additional scopes can be added by defining a @Singleton bean that implements the CustomScope interface.

Note that with Micronaut when starting an ApplicationContext by default @Singleton scoped beans are created lazily and on demand. This is by design and to optimize startup time.

If this presents a problem for your use case you have the option of using the @Context annotation which binds the lifecycle of your object to the lifecycle of the ApplicationContext. In other words when the ApplicationContext is started your bean will be created.

Alternatively you can annotate any @Singleton scoped bean with @Parallel which allows parallel initialization of your bean without impacting overall startup time.

If your bean fails to initialize in parallel then the application will be automatically shutdown.