1. Guice

1) Add Guice dependency to your project:

Maven
Gradle
<dependency>
  <groupId>io.jooby</groupId>
  <artifactId>jooby-guice</artifactId>
  <version>3.0.10</version>
</dependency>

2) Install Guice:

Installing Guice
Java
Kotlin
import io.jooby.guice.GuiceModule;
import io.jooby.kt.runApp;

public class App extends Jooby {

  {
    install(new GuiceModule());                     (1)

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

  public static void main(String[] args) {
    runApp(args, App::new);
  }
}
1 Install Guice module
2 The require(Class) call is now resolved by Guice

1.1. Property Injection

Configuration properties can be injected using the @Named annotation:

application.conf
currency = USD
Java
Kotlin
import javax.injext.Named;
import javax.injext.Inject;

public class BillingService {

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

}

1.2. MVC routes

Guice will also provisioning MVC routes

MVC and Guice
Java
Kotlin
import io.jooby.guice.GuiceModule;
import io.jooby.kt.runApp

public class App extends Jooby {

  {
    install(new GuiceModule());  (1)

    mvc(MyController.class);     (2)
  }

  public static void main(String[] args) {
    runApp(args, App::new);
  }
}
1 Install Guice module
2 Register a MVC route

The lifecycle of MyController is now managed by Guice. Also:

  • In Guice, the default scope is prototype (creates a new instance per request)

  • If you prefer a single instance add the jakarta.inject.Singleton annotation