How is the Inversion of Control effect achieved in Quarkus through dependency injection?
sobes.tech AI
Answer from AI
In Quarkus, the effect of Inversion of Control (IoC) is achieved through the Dependency Injection (DI) mechanism, based on the CDI (Contexts and Dependency Injection) specification. Quarkus automatically scans classes and components marked with annotations such as @Inject, @ApplicationScoped, @Singleton, and others, and manages their lifecycle.
When a dependency is needed in the code, Quarkus automatically injects the required object, freeing the developer from manually creating instances and managing them. This makes it easy to replace implementations, simplifies testing, and increases the modularity of the application.
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 a Service object itself but receives it from the Quarkus container via DI, which is an expression of IoC.