Jooby

Avaje Inject

1) Add Avaje Inject to your project

Maven
Gradle
<dependency>
  <groupId>io.jooby</groupId>
  <artifactId>jooby-avaje-inject</artifactId>
  <version>4.1.0</version>
</dependency>

2) Configure annotation processor

Maven
Gradle
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>...</version>
      <configuration>
        <annotationProcessorPaths>
          <!-- if using lombok, it must be placed before the avaje-inject-generator -->
          <!-- avaje-inject-generator must be placed before the jooby-apt -->
          <path>
            <groupId>io.avaje</groupId>
            <artifactId>avaje-inject-generator</artifactId>
            <version>12.4</version>
          </path>
        </annotationProcessorPaths>
      </configuration>
    </plugin>
  </plugins>
</build>
Note

Please note that the order of annotation processors is important. For example, if you’re using lombok and avaje-inject, the correct order should be: lombokavaje-injectjooby-apt

3) Install Avaje Inject:

Installing Avaje Inject
Java
Kotlin
public class App extends Jooby {

  {
    install(AvajeInjectModule.of());                (1)

    get("/", ctx -> {
      MyService service = require(MyService.class); (2)
      return service.doSomething();
    });
}

  public static void main(String[] args) {
    runApp(args, App::new);
  }
}
  1. Install Avaje Inject module

  2. The require(Class) call is now resolved by Avaje Inject

Property Injection

Configuration properties can be injected using the @Named annotation. As Avaje checks beans at compile time, @External is required to prevent false-positive compilation errors:

application.conf
currency = USD
Java
Kotlin
@Singleton
public class BillingService {

  @Inject
  public BillingService(@External @Named("currency") String currency) {
    ...
  }

}
MVC routes

Avaje Inject will also provisioning MVC routes

MVC and Avaje Inject
Java
Kotlin
public class App extends Jooby {

  {
    install(AvajeInjectModule.of());  (1)

    mvc(MyController.class);          (2)
  }

  public static void main(String[] args) {
    runApp(args, App::new);
  }
}
  1. Install Avaje Inject module

  2. Register a MVC route

The lifecycle of MyController is now managed by Avaje Inject.

In Avaje Inject, the dependency graph is typically validated when the application compiles. As beans provided by Jooby Modules are registered at runtime, you must add @External when injecting these runtime beans into @Singleton classes to inform the avaje processor that these beans are provided at runtime.