CDI-based Dependency Injection
In the previous step, you created a basic RESTful Java application with Quarkus. In this step, we'll add a custom bean that will use the ArC extension which provides a CDI-based dependency injection solution tailored for the Quarkus architecture.
Adding a Custom Bean
Let’s modify the application and add a companion bean. Before we get started, keep in mind that we can leave the application running; we don't need to stop and restart it to pick up the changes. Create the following file:
src/main/java/org/acme/quickstart/GreetingService.java
and add the following contents:
package org.acme.quickstart;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class GreetingService {
private String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");
public String greeting(String name) {
return "hello " + name + " from " + hostname;
}
}
GreetingResource.java
file. For simplicity, you can replace its existing contents with the following:
package org.acme.quickstart;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/hello")
public class GreetingResource {
@Inject
GreetingService service;
@GET
@Path("/greeting/{name}")
public String greeting(String name) {
return service.greeting(name);
}
@GET
public String hello() {
return "Hello from RESTEasy Reactive";
}
}
Inspecting the Results
mvn quarkus:dev
, when you make these changes and reload the endpoint, Quarkus will notice all of these changes and reload them automatically.
curl localhost:8080/hello/greeting/quarkus
The result should be similar to the following:
hello quarkus from demo
In this case, demo
is the hostname of the local host the Quarkus process is running on. It will be different when it's deployed to Kubernetes.