Groovy / Maven

Micronaut Scope Types

Learn about the available scopes: Singleton, Prototype, Request, Refreshable, Context...

Sergio del Amo
On this guide
In this section

Introduction

Micronaut features an extensible bean scoping mechanism based on JSR-330.

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=management,validation \
    --build=maven \
    --lang=groovy \
    --test=spock
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add management, and validation features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

Scenario

We use the following scenario to talk about the different types of scopes.

The following @Controller injects two collaborators.

groovy/src/main/groovy/example/micronaut/singleton/RobotController.groovy

Each collaborator has an injection point for a bean of type Robot.

groovy/src/main/groovy/example/micronaut/singleton/RobotFather.groovy
groovy/src/main/groovy/example/micronaut/singleton/RobotMother.groovy

Let’s discuss how the application behaves depending on the scope used for the bean of type Robot.

Singleton

Singleton scope indicates only one instance of the bean will exist.

To define a singleton, annotate a class with jakarta.inject.Singleton at the class level.

The following class creates a unique identifier in the constructor. This identifier allows us to identify how many Robot instances are used.

groovy/src/main/groovy/example/micronaut/singleton/Robot.groovy

Singleton Test

The following test verifies @Singleton behavior.

groovy/src/test/groovy/example/micronaut/SingletonScopeSpec.groovy

Prototype

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

Let’s use @Prototype instead of @Singleton.

groovy/src/main/groovy/example/micronaut/prototype/Robot.groovy

Prototype Tests

The following test verifies the behavior of Prototype scope.

groovy/src/test/groovy/example/micronaut/PrototypeScopeSpec.groovy

Request

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

groovy/src/main/groovy/example/micronaut/request/Robot.groovy

Request Tests

The following test verifies the behavior of @RequestScope scope.

groovy/src/test/groovy/example/micronaut/RequestScopeSpec.groovy

Refreshable

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

groovy/src/main/groovy/example/micronaut/refreshable/Robot.groovy

Your application needs the management dependency to enable the refresh endpoint.

pom.xml
<dependency>
    <groupId>io.micronaut</groupId>
    <artifactId>micronaut-management</artifactId>
    <scope>compile</scope>
</dependency>

Refreshable Tests

The following test enables the refresh endpoint and verifies the behavior of @Refreshable

groovy/src/test/groovy/example/micronaut/RefreshableScopeSpec.groovy

@Context

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

The following example uses @Context in combination with @ConfigurationProperties.

groovy/src/main/groovy/example/micronaut/context/FrameworkConfiguration.groovy

The result is validation being performed on the Application Context start-up.

groovy/src/test/groovy/example/micronaut/ContextSpec.groovy
package example.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.context.exceptions.BeanInstantiationException
import spock.lang.Specification

class ContextSpec extends Specification {

    void 'life cycle of classes annotated with Context is bound to that of the BeanContext'() {
        when:
        ApplicationContext.run(['framework.language': 'scala'])

        then:
        BeanInstantiationException e = thrown()
        e.message.contains('must match "groovy|java|kotlin"')
    }
}

Other scopes

Micronaut Framework ships with other built-in scopes:

@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

Next Steps

Read more about Scopes in the Micronaut Framework.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).