Sobes.tech
Junior — Middle

How is dependency injection and inversion of control implemented in Quarkus applications using the Dependency Injection pattern?

sobes.tech AI

Answer from AI

Dependency Injection (DI) and Inversion of Control (IoC) in Quarkus are implemented using the standard CDI (Contexts and Dependency Injection) specifications. This allows for automatic management of component creation and wiring.

Key points:

  • Classes to be injected are annotated, for example, with @Inject for fields or constructors.
  • Quarkus automatically creates and manages the lifecycle of these dependencies.
  • Inversion of Control means that instead of manually creating objects, you declare dependencies, and the Quarkus container provides the necessary instances.

Example:

import javax.inject.Inject;
import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class Service {
    public String serve() {
        return "Service is working";
    }
}

@ApplicationScoped
public class Consumer {
    @Inject
    Service service;

    public void doWork() {
        System.out.println(service.serve());
    }
}

Here, Consumer does not create the Service object itself but receives it from the container via DI. This simplifies testing, modularity, and dependency management.

How is dependency injection and inversion of control… - sobes.tech