Guice
1) Add Guice dependency to your project:
Maven
Gradle
<dependency>
<groupId>io.jooby</groupId>
<artifactId>jooby-guice</artifactId>
<version>4.0.16</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);
}
}
-
Install Guice module
-
The require(Class) call is now resolved by Guice
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) {
...
}
}
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);
}
}
-
Install Guice module
-
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.Singletonannotation