3 Inversion of Control

When most developers think of Inversion of Control (also known as Dependency Injection and referred to as such from this point onwards) the Spring Framework comes to mind.

Micronaut takes inspiration from Spring, and in fact, the core developers of Micronaut are former SpringSource/Pivotal engineers now working for OCI.

Unlike Spring which relies exclusively 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’s 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 Spring 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 itself for whatever application type you may wish to build. To do so all you need to do is configure your build appropriately to include the micronaut-inject-java dependency as an annotation processor. For example with Gradle:

Configuring Gradle

  1. plugins {
  2. id "com.diffplug.eclipse.apt" version "3.22.0" // <1>
  3. }
  4. ...
  5. dependencies {
  6. annotationProcessor("io.micronaut:micronaut-inject-java:2.1.4") // <2>
  7. implementation("io.micronaut:micronaut-inject:2.1.4")
  8. ...
  9. testAnnotationProcessor("io.micronaut:micronaut-inject-java:2.1.4") // <3>
  10. ...
  11. }
1Apply com.diffplug.eclipse.apt Gradle plugin which modifes Eclipse projects to include gradle annotationProcessor dependencies
2Include the minimal dependencies required to perform dependency injection
3This is necessary to create beans in the test directory
For the Groovy language you should include micronaut-inject-groovy in the compileOnly and testCompileOnly scopes.

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 that has been dependency injected
The example uses Java’s try-with-resources syntax to ensure the ApplicationContext is cleanly shutdown when the application exits.