Estimate project
← All posts

Getting started with Micronaut IOC: the basics

The goal of this article is to give a thorough introduction to the Micronaut IOC container – its details, features, and use cases. It explores typical use cases and points out best practices for working with the container.

9 min read
MicronautJavaframeworks

The goal of this article is to give a thorough introduction to the Micronaut IOC container – its details, features, and use cases. It explores typical use cases and points out best practices for working with the container. On top of that, there is a section with tips, personal experience, and know-how, aimed especially at readers coming from Spring Boot, to make the move to Micronaut easier.

Inversion of Control (IOC) container

An IOC container is responsible for creating objects – injecting the dependencies declared for them beforehand – and for managing those objects afterwards. Such objects are called beans, and they are built according to a supplied definition. We can declare them either by marking our classes as beans or by writing factory methods. This way, the container rather than our code is in charge of initializing objects.

The Micronaut IoC container implements JSR-330 and uses AOT compilation to keep reflection to a minimum and shorten application startup, which makes it lightweight and suitable for native compilation. It is a module independent of the rest of the framework, so it can be used in the same way as the well-known Guice or Dagger.

Dependency Injection (DI) types

As with most IoC containers, Micronaut offers 3 ways of injecting dependencies with the @Inject annotation

Constructor

class Car {

    private final Engine engine;

    @Inject
    public Car(Engine engine) {
        this.engine = engine;
    }

If a class has just one constructor, the @Inject annotation is unnecessary, since the container picks that constructor on its own. When there are several constructors, one of them has to be annotated.

Method/Setter

class Car {

    private Engine engine;

    @Inject
    public void setEngine(Engine engine) {
        this.engine = engine;
    }

Field

class Car {

    @Inject
    Engine engine;

}

Still, constructor injection is the most recommended option, because it lets you require dependencies at the moment the object is created, and together with the final keyword it gives stronger null safety. Constructor injection also makes code easier to test, since in a unit test you can pass in mocks without an IoC container. Setter and field injection should be treated as a last resort, used only when nothing else is possible.

Dependencies

Below are the minimal dependencies required to run the Micronaut IoC container and the examples from this tutorial. Alternatively, you can generate a sample project at micronaut.io/launch. The examples that follow use Micronaut version 3.8.2 and JDK 17.

Gradle

plugins {
id 'io.micronaut.library' version '1.3.2'
}

micronaut {
version("3.8.2")
}

...

dependencies {
annotationProcessor "io.micronaut:micronaut-inject-java"
implementation "io.micronaut:micronaut-inject"
implementation "io.micronaut:micronaut-runtime"
testImplementation "io.micronaut.test:micronaut-test-junit5"
testImplementation "org.junit.jupiter:junit-jupiter-engine:5.9.1"
}

Scopes

Under the JSR-330 specification, a bean’s lifecycle is determined by its Scope. The scope tells the IOC container when to instantiate beans and how to handle the existing ones, following predefined rules. Micronaut provides 7 scopes – some come straight from the specification, while the others were added by the framework’s authors.

Available scopes

  • Singleton - a scope for a bean that may have just a single instance,
    created lazily when it is first injected
  • Context - a scope close to singleton, but its lifecycle is tied to BeanContext and the bean is created eagerly when the context starts. The authors recommend @Singleton as the default choice; reach for @Context only if you need eager initialization, as it has an impact on application startup
  • Prototype - the default bean scope, where every injection gets a fresh instance
  • RequestScope - a scope for a bean whose lifecycle is bound to the HTTP request; it needs an HTTP module
  • Infrastructure - a scope for a critical bean that cannot be replaced with @Replaces. Useful for authors of libraries and extensions
  • ThreadLocal - a scope that creates a separate bean instance for every thread
  • Refreshable - a scope whose bean state is refreshed through /refresh or by publishing a RefreshEvent

Keep in mind that the default bean scope is prototype, in contrast to the popular Spring Boot, where Singleton is the default. We will concentrate on the last three, since in my view they set Micronaut apart from other popular IoC containers.

Infrastructure

Imagine a critical bean that computes the area of a rectangle, and we don’t want anyone to swap it out, since that could break the application. That is why we apply the @Infrastructure annotation.

@Infrastructure
public class RectangleAreaCalculator {

    public double calculate(double a, double b) {
        return a * b;
    }

What if a user attempts to override the bean by putting @Replaces on a subclass with a faulty implementation?

@Singleton
@Replaces(RectangleAreaCalculator.class)
public class InvalidRectangleAreaCalculator extends RectangleAreaCalculator {

    @Override
    public double calculate(double a, double b) {
    return a - b;
    }

In reality, nothing happens: the InvalidRectangleAreaCalculator bean is neither created nor used in place of RectangleAreaCalculator.

@MicronautTest
class InfrastructureTest {

    @Inject
    RectangleAreaCalculator rectangleAreaCalculator;

    @Test
    void infrastructureBeanDoesNotGetReplaced() {
        Assertions.assertInstanceOf(RectangleAreaCalculator.class, rectangleAreaCalculator);
        Assertions.assertEquals(20, rectangleAreaCalculator.calculate(4, 5));
    }

ThreadLocal

Before getting to the scope itself, it helps to know that the Java API includes a ThreadLocal mechanism. It ensures that every thread invoking the .get() method of ThreadLocal receives its own separate object instance. You can picture it as a HashMap in which the thread acts as the implicit key.

At initialization, we need to implement a functional interface whose method returns the starting value.

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 27);

After that, the get() method gives us an instance unique to the current thread.

    Integer myUniqueInteger = threadLocal.get();

Here, the starting value is our bean definition. Internally, this scope is implemented with a proxy that holds a ThreadLocal variable and forwards method calls to the right instance. Thanks to that, a bean can be shared among other beans running in the same thread.

With the theory covered, let’s look at an example. We’ll create a simple bean whose only job is to hold a String.

@ThreadLocal
public class ThreadLocalStorage {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

Following the idea behind the ThreadLocal scope, every thread should point to its own instance of the bean. As a result, the value of the “text” field is shared only inside a single thread, as the test below demonstrates.

@MicronautTest
class ThreadLocalExampleTest {

    @Inject
    ThreadLocalStorage storage;

    @Test
    void test() {
        storage.setText("Main test thread");
        assertEquals("Main test thread", storage.getText());

        runBlockingInNewThread(() -> {
            assertNull(storage.getText()); (1)
            storage.setText("Sub-thread in test");
            assertEquals("Sub-thread in test", storage.getText());

            runBlockingInNewThread(() -> {
                assertNull(storage.getText());
                storage.setText("Sub-sub-thread in test");
                assertEquals("Sub-sub-thread in test", storage.getText());
            });

            assertEquals("Sub-thread in test", storage.getText()); (2)
        });

        assertEquals("Main test thread", storage.getText());
    }

    private void runBlockingInNewThread(Runnable runnable) throws RuntimeException {
        try {
            final var thread = new Thread(runnable);
            thread.start();
            thread.join();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

(1) This thread must not see the text set in the main text thread, so the value should be null.

(2) We verify that the inner thread did not overwrite the value.
The test above shows that the order of method calls on a given bean is irrelevant. State carried between calls matters only inside one thread.

Refreshable

The Refreshable scope allows us to refresh our bean’s state. In practice, the method annotated with @PostConstruct gets invoked on the bean once more. Possible uses for this scope include reloading a bean’s configuration, clearing a cache, or triggering any other side effect. Would I rely on it in practice? That deserves a separate article, but the option is there.

For the example, we’ll write a class called RefreshableSeed with an init() method and a latestSeed() method.

@Refreshable
public class RefreshableSeed {

    private int seed;

    @PostConstruct
    public void init() {
    seed = new Random().nextInt();
    }

    public int latestSeed() {
    return seed;
    }

As noted before, there are two ways to refresh the state. One is the /refresh endpoint that Micronaut defines out of the box, though it needs an HTTP module

Publishing RefreshEvent using ApplicationEventPublisher
eventPublisher.publishEvent(new RefreshEvent());

For the test and the demo, we’ll go with the event publisher approach.

@MicronautTest
class RefreshableSeedTest {

    @Inject
    RefreshableSeed refreshableSeed;

    @Inject
    ApplicationEventPublisher<RefreshEvent> eventPublisher;

    @Test
    void refreshableBeanGetsRefreshedWithRefreshEvent() {
        final var firstSeed = refreshableSeed.latestSeed();

        // Should not change before event
        assertEquals(firstSeed, refreshableSeed.latestSeed());

        eventPublisher.publishEvent(new RefreshEvent());

        assertNotEquals(firstSeed, refreshableSeed.latestSeed());
    }

The test above shows that firing the event changed only the bean’s state.

Coming from Spring

A lot of people picking up Micronaut have previously worked with Spring. The framework’s authors know this too, and they build dedicated modules like Micronaut for Spring to ease migrating existing applications into the Micronaut ecosystem. The drawback of such a module is that it solves the problem only in part, since you end up mixing code from two different frameworks. In my opinion, these modules are not the best way to go, so instead I will highlight the key differences that matter to Spring Developers.

The default scope differs

The biggest difference is that the default scope of the Micronaut Container is Prototype, an alias for @Bean, and not Singleton as in Spring Boot. I recommend being explicit and using the annotations that actually define the scope, such as @Singleton or @Prototype, rather than depending on the defaults.

Singleton scope does not behave the same

The Singleton scope differs from the one in Spring Boot. In Micronaut, a Singleton is lazy by default – it is not created when the context starts, but only when it is needed. What really corresponds to @Scope(“Singleton”) from Spring Boot is @Context. This is a deliberate choice: the authors built it like that to cut application startup time even more. For that reason, use eager initialization only when you genuinely have solid reasons or justification for it.

Spring Boot Micronaut
@Component @Context
@Lazy @Component @Singleton

Eager singleton in Micronaut

As said before, lazy singleton initialization is the preferred approach and should be your first choice. If you do have a reason for eager initialization, though, there are a few options.

  1. Apply the @Context scope
  2. Configure the bean context, which however applies to every singleton
public class MicronautApp {

    public static void main(String[] args) {
        Micronaut.build(args)
            .eagerInitSingletons(true)
            .mainClass(Application.class)
            .start();
    }
}
  1. Combine the @Parallel annotation with @Singleton

Annotation Cheat Sheet

I’ve also put together a short cheat-sheet of annotations commonly used in Spring Boot to help you find their Micronaut counterparts.

Spring Micronaut
@Component The direct 1:1 counterpart is@Context, but prefer @Singleton. Reserve Context for cases where eager initialization is truly required.
@Service The direct 1:1 counterpart is@Context, but prefer @Singleton. Reserve Context for cases where eager initialization is truly required.
@Repository @Repository
@RestController @Controller
@Bean The direct 1:1 counterpart is@Context, but prefer @Singleton. Reserve Context for cases where eager initialization is truly required.@Bean does not correspond, since Micronaut’s default scope is @Prototype
@Scope @Singleton @Context @Prototype @Infrastructure @ThreadLocal @Refreshable @RequestScope
@Autowired @Inject
@Value @Value
@Qualifier @Named
@Configuration @Factory
@Profile(“test”) @Requires(env=“test”)
@Import @Import
@Primary @Primary

Summary

I hope this article was useful to you and gave you a solid basic introduction to IoC in Micronaut, whatever your past experience with the Spring Framework. In the next blog post, we will explore bean containers, conditional beans, and how they can be used. Stay tuned!