Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING

1. Introduction

From the creator of ebean, Avaje Inject is a JVM-based framework for advanced compile-time Dependency Injection (DI). It takes the approach of generating readable source code to support various DI operations. Avaje reads JSR-330 annotated beans and generates classes to collect bean instances from our application and use them at the appropriate time.

2. Dependency Injection

As a bit of a reminder, Dependency Injection is a concrete application of the Inversion of Control principle in which the program controls its own flow.

Different frameworks implement dependency injection in different ways. In particular, one of the most notable of these differences is whether the injection happens at run-time or compile-time.

Run-time DI is usually based on reflection. It’s simple to use but slow at runtime. The premier example of a runtime DI framework is Spring.

Compile-time DI, on the other hand, is typically based on code generation. This means that all the heavyweight operations are performed during the compilation stage. It generally performs faster as it eliminates the need for intensive reflection or classpath scanning at runtime.

Avaje has decided to rely totally on annotation processing for compile-time source generation.

3. Maven/Gradle Configuration

To use Avaje Inject in a project, we’ll need to add the avaje-inject dependencies to our pom.xml:

<dependency>
    <groupId>io.avaje</groupId>
    <artifactId>avaje-inject</artifactId>
    <version>9.5</version>
</dependency>

<dependency>
    <groupId>io.avaje</groupId>
    <artifactId>avaje-inject-test</artifactId>
    <version>9.5</version>
    <scope>test</scope>
</dependency>

Furthermore, we’ll also need to include the inject code generator to read our annotated classes and generate the code used for the injection. It’s added with an optional scope because the generator is only required at compile time:

<dependency> 
    <groupId>io.avaje</groupId>
    <artifactId>avaje-inject-generator</artifactId>
    <version>9.5</version>
    <scope>provided</scope>
    <optional>true</optional>
</dependency>

If we’re using Gradle, we’ll include these dependencies as:

implementation('io.avaje:avaje-inject:9.5')
annotationProcessor('io.avaje:avaje-inject-generator:9.5')

testImplementation('io.avaje:avaje-inject-test:9.5')
testAnnotationProcessor('io.avaje:avaje-inject-generator:9.5')

Now that we have avaje-inject in our project, let’s create a sample application to see how it works.

4. Implementation

For our example, we’ll try to build a knight by injecting his weapons as dependencies. The avaje-inject generator will read all various annotations at compile-time and generate DI code in target/generated-sources/annotations.

4.1. @Singleton and @Inject

In a similar manner to Spring’s @Component, Avaje uses the standard JSR-330 annotation @Singleton to mark a class as a bean. To inject dependencies, we add the @Inject annotations to fields or the constructor. The generated DI code is in the same package, so to use field/method injection, those elements must be public or package-private.

Let’s have a look at our Knight class, which has two weapon dependencies:

@Singleton
public class Knight {

  private Sword sword;

  private Shield shield;

  @Inject
  public Knight(Sword sword, Shield shield) {
    this.sword = sword;
    this.shield = shield;
  }
  //standard getters and setters
}

The code generator will read the annotations and generate a class to gather the dependencies and register the bean:

@Generated("io.avaje.inject.generator")
public final class Knight$DI  {

  public static void build(Builder builder) {
    if (builder.isAddBeanFor(Knight.class)) {
      var bean = new Knight(builder.get(Sword.class,"!sword"), builder.get(Shield.class,"!shield"));
      builder.register(bean);
    }
  }
}

This class checks for existing Knight classes and then retrieves the dependencies from the current scope.

4.2. @Factory and @Bean

Like Spring’s @Configuration classes, we can annotate a class with @Factory and its methods with @Bean to mark the class as a factory that creates beans.

In the ArmsFactory class, we use this to provide the knight’s armaments to the application scope:

@Factory
public class ArmsFactory {

  @Bean
  public Sword provideSword() {
    return new Sword();
  }

  @Bean
  public Brand provideShield() {
    return new Shield(25);
  }
}

The code generator will read the annotations and generate a class to call the constructors and factory methods:

@Generated("io.avaje.inject.generator")
public final class ArmsFactory$DI  {

  public static void build(Builder builder) {
    if (builder.isAddBeanFor(ArmsFactory.class)) {
      var bean = new ArmsFactory();
      builder.register(bean);
    }
  }

  public static void build_provideEngine(Builder builder) {
    if (builder.isAddBeanFor(Sword.class)) {
      var factory = builder.get(ArmsFactory.class);
      var bean = factory.provideEngine();
      builder.register(bean);
    }
  }

  public static void build_provideBrand(Builder builder) {
    if (builder.isAddBeanFor(Shield.class)) {
      var factory = builder.get(ArmsFactory.class);
      var bean = factory.provideBrand();
      builder.register(bean);
    }
  }
}

4.3. @PostConstruct and @PreDestroy

Avaje can use lifecycle methods to attach custom actions to bean creation and destruction. @PostConstruct methods execute after the BeanScope finishes wiring all the beans, and @Predestroy runs when the BeanScope is closed.

Given that @PostConstruct methods will execute after all beans have wired, we can add a BeanScope parameter to configure further using the completed BeanScope. The below Ninja class uses @PostConstruct to set its members with beans from the application scope:

@Singleton
public class Ninja {

  private Sword sword;

  @PostConstruct
  void equip(BeanScope scope) {
    sword = scope.get(Sword.class);
  }

  @PreDestroy
  void dequip() {
    sword = null;
  }

//getters/setters
}

The code generator will read the annotations and generate a class to call the constructor and register the lifecycle methods:

@Generated("io.avaje.inject.generator")
public final class Ninja$DI  {

  public static void build(Builder builder) {
    if (builder.isAddBeanFor(Ninja.class)) {
      var bean = new Ninja();
      var $bean = builder.register(bean);
      builder.addPostConstruct($bean::equip);
      builder.addPreDestroy($bean::dequip);
    }
  }
}

5. Generated Module

At compile time, the avaje-inject-generator reads all the bean definitions and determines the wiring of all the beans. It then generates a Module class representing our application and its dependencies.

For all the above classes, the below IntroModule is generated to execute all the injections to add to the application scope. We can see the definition and wiring order of all the beans in the application:

@Generated("io.avaje.inject.generator")
@InjectModule()
public final class IntroModule implements Module {

  private Builder builder;

  @Override
  public Class<?>[] classes() {
    return new Class<?>[]{
      com.baeldung.avaje.intro.ArmsFactory.class,
      com.baeldung.avaje.intro.Knight.class,
      com.baeldung.avaje.intro.Ninja.class,
      com.baeldung.avaje.intro.Shield.class,
      com.baeldung.avaje.intro.Sword.class,
    };
  }

  /**
   * Creates all the beans in order based on constructor dependencies.
   * The beans are registered into the builder along with callbacks for
   * field/method injection, and lifecycle support.
   */
  @Override
  public void build(Builder builder) {
    this.builder = builder;
    build_intro_ArmsFactory();
    build_intro_Ninja();
    build_intro_Sword();
    build_intro_Shield();
    build_intro_Knight();
  }

  @DependencyMeta(type = "com.baeldung.avaje.intro.ArmsFactory")
  private void build_intro_ArmsFactory() {
    ArmsFactory$DI.build(builder);
  }

  @DependencyMeta(type = "com.baeldung.avaje.intro.Ninja")
  private void build_intro_Ninja() {
    Ninja$DI.build(builder);
  }

  @DependencyMeta(
      type = "com.baeldung.avaje.intro.Sword",
      method = "com.baeldung.avaje.intro.ArmsFactory$DI.build_provideSword",
      dependsOn = {"com.baeldung.avaje.intro.ArmsFactory"})
  private void build_intro_Sword() {
    ArmsFactory$DI.build_provideSword(builder);
  }

  @DependencyMeta(
      type = "com.baeldung.avaje.intro.Shield",
      method = "com.baeldung.avaje.intro.ArmsFactory$DI.build_provideShield",
      dependsOn = {"com.baeldung.avaje.intro.ArmsFactory"})
  private void build_intro_Shield() {
    ArmsFactory$DI.build_provideShield(builder);
  }

  @DependencyMeta(
      type = "com.baeldung.avaje.intro.Knight",
      dependsOn = {
        "com.baeldung.avaje.intro.Sword",
        "com.baeldung.avaje.intro.Shield"
      })
  private void build_intro_Knight() {
    Knight$DI.build(builder);
  }
}

6. Retrieving Beans With BeanScope

To manage dependencies, Avaje’s BeanScope loads and executes all the generated Module classes from the application and its dependencies and stores the created beans to be retrieved later.

Let’s construct the BeanScope and receive our Knight class, fully equipped with Sword and Shield:

final var scope = BeanScope.builder().build();
final var knight = scope.get(Knight.class);

assertNotNull(knight);
assertNotNull(knight.sword());
assertNotNull(knight.shield());
assertEquals(25, knight.shield().defense());

7. Component Testing With @InjectTest

The @InjectTest annotation is useful when we need to bootstrap a bean scope for our tests. The annotation works by creating a test BeanScope that will be utilized.

We can use Mockito’s @Mock annotation to add mock objects to the test’s BeanScope. When we use the @Mock annotation on a field, the mock will be injected into the field, as well as registered in the test scope. The mock will replace any existing bean of the same type in the scope.

If no bean of the same type is defined, a new one will be added. This is useful for component tests where a particular bean, like an external service, needs to be mocked.

Here, we use the injected Shield mock to stub the defense method. Then, we use @Inject to get the knight bean from the test scope to verify that it contains the mocked shield:

@InjectTest
class ExampleInjectTest {

  @Mock Shield shield;

  @Inject Knight knight;

  @Test
  void givenMockedShield_whenGetShield_thenShieldShouldHaveMockedValue() {

    Mockito.when(shield.defense()).thenReturn(0);
    assertNotNull(knight);
    assertNotNull(knight.sword());
    assertEquals(knight.shield(), shield);
    assertEquals(0, knight.shield().defense());
  }
}

8. Conclusion

In this article, we went through how to set up and use Avaje Inject with a basic example. We’ve seen how it uses code generation to perform various DI actions and how to create tests and use mocks.

As always, all the code in the article is available over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!