3 Inversion of Control

Unlike other frameworks which rely on runtime reflection and proxies, Micronaut uses compile time data to implement dependency injection.

This is a similar approach taken by tools such as Google Dagger, which is designed primarily with Android in mind. Micronaut, on the other hand, is designed for building server-side microservices and provides many of the same tools and utilities as other frameworks but without using reflection or caching excessive amounts of reflection metadata.

The goals of the Micronaut IoC container are summarized as:

  • Use reflection as a last resort

  • Avoid proxies

  • Optimize start-up time

  • Reduce memory footprint

  • Provide clear, understandable error handling

Note that the IoC part of Micronaut can be used completely independently of Micronaut for whatever application type you wish to build.

To do so, configure your build to include the micronaut-inject-java dependency as an annotation processor.

The easiest way to do this is with Micronaut’s Gradle or Maven plugins. For example with Gradle:

Configuring Gradle

  1. plugins {
  2. id 'io.micronaut.library' version '1.3.2' (1)
  3. }
  4. version "0.1"
  5. group "com.example"
  6. repositories {
  7. mavenCentral()
  8. }
  9. micronaut {
  10. version = "3.0.0" (2)
  11. }
1Define the Micronaut Library plugin
2Specify the Micronaut version to use

The entry point for IoC is then the ApplicationContext interface, which includes a run method. The following example demonstrates using it:

Running the ApplicationContext

  1. try (ApplicationContext context = ApplicationContext.run()) { (1)
  2. MyBean myBean = context.getBean(MyBean.class); (2)
  3. // do something with your bean
  4. }
1Run the ApplicationContext
2Retrieve a bean from the ApplicationContext
The example uses Java try-with-resources syntax to ensure the ApplicationContext is cleanly shutdown when the application exits.