Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Dependency Injection and CDI

CDI Beans and Injection

Learn dependency injection in Quarkus with CDI: what a bean is, how @Inject works with constructors and fields, how ArC resolves types and common errors.

Dependency injection (DI) is the idea that a class receives the objects it needs instead of creating them itself. It keeps code easy to test and to change: a PriceService that needs a TaxCalculator should not decide which calculator, how it is built or how long it lives. Quarkus uses CDI (Contexts and Dependency Injection, the Jakarta standard) for this, implemented by its own container called ArC.

In this lesson you will learn what a bean is, the different ways to inject, how Quarkus decides which bean to inject and what the typical errors mean. The real annotations are read-only. The runnable examples are plain-Java containers that rebuild the resolution logic so you can see it work.

Beans

A bean is an object that the container creates, wires and manages. In Quarkus you declare one by annotating a class with a scope annotation, most often @ApplicationScoped:

Java
package org.acme;

import jakarta.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class TaxCalculator {

    public double withTax(double net) {
        return net * 1.20;
    }
}

Any other bean can now ask for it with @Inject:

Java
package org.acme;

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

@ApplicationScoped
public class PriceService {

    @Inject
    TaxCalculator taxCalculator;

    public double gross(double net) {
        return taxCalculator.withTax(net);
    }
}

You never write new TaxCalculator(). The container creates one instance, keeps it for the lifetime defined by the scope and hands it to every @Inject point that asks for it. Bean Scopes covers lifetimes.

How injection works

Declare Put a scope annotation on the class.
Find Build time: match injection points to beans by type.
Create The container instantiates and wires the bean.
Inject Your class receives a ready object.

Resolution is checked at build time, so wiring errors fail the build.

1 / 2

Three injection styles

Field injection is the shortest. Quarkus encourages package-private fields (no private) so it can set them without reflection:

Java
@ApplicationScoped
public class OrderService {
    @Inject
    PriceService priceService;     // package-private: no reflection needed
}

Constructor injection keeps fields final and makes the class easy to create in a plain unit test. With a single constructor, @Inject is optional in Quarkus:

Java
@ApplicationScoped
public class OrderService {
    private final PriceService priceService;

    OrderService(PriceService priceService) {
        this.priceService = priceService;
    }
}

Setter (initializer) injection is rare:

Java
@Inject
void setPriceService(PriceService priceService) {
    this.priceService = priceService;
}

Which should you use? For new code, constructor injection is a good default because dependencies are explicit and unit tests simply call the constructor. Package-private field injection is shorter and perfectly accepted in Quarkus code, and it is what most guides show. Pick one style per project. One caution: a normal-scoped bean (like @ApplicationScoped) needs a no-argument constructor for its client proxy. Quarkus generates one for you, so you can still write a single injecting constructor.

Which bean gets injected?

CDI resolves by type. For an injection point of type T, the container looks for beans whose type set contains T. A bean's types include its class, all superclasses and all interfaces. So you can inject an interface:

Java
public interface Notifier {
    void notify(String message);
}

@ApplicationScoped
public class EmailNotifier implements Notifier {
    public void notify(String message) { /* send email */ }
}

@ApplicationScoped
public class Alerts {
    @Inject
    Notifier notifier;      // resolves to EmailNotifier
}

If exactly one bean matches, injection works. If none match you get an unsatisfied dependency; if several match you get an ambiguous dependency. Quarkus reports both at build time, so you never find out in production.

Text
Unsatisfied dependency for type org.acme.Notifier and qualifiers [@Default]
  - java member: org.acme.Alerts#notifier
Ambiguous dependencies for type org.acme.Notifier and qualifiers [@Default]
  - available beans: org.acme.EmailNotifier, org.acme.SmsNotifier

You solve ambiguity with qualifiers, @Alternative or @DefaultBean, covered in Qualifiers and Producers.

A mini container

The next stand-in is a tiny dependency injection container built with reflection. It registers classes, then creates instances by looking at constructor parameter types and recursively building them. It also keeps one instance per class, like an @ApplicationScoped bean. It is not how ArC works (ArC does all this at build time and generates code), but the resolution idea is the same.

Java Stand-in: constructor injection by type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how asking for OrderService first created TaxCalculator, then PriceService, then OrderService: dependencies are built bottom-up. The second request created nothing, because the instances are kept. The last call fails with an unsatisfied dependency, the same kind of error Quarkus reports (but at build time).

Resolving by interface

The next stand-in models type resolution when several implementations exist. It uses the same three outcomes as CDI: exactly one match works, none is "unsatisfied", more than one is "ambiguous".

Java Stand-in: unsatisfied and ambiguous resolution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

ArC rules worth knowing

Quarkus implements the CDI Lite model through ArC, with a few practical differences from a full Jakarta EE server:

  • No beans.xml needed. Classes with a bean-defining annotation (a scope such as @ApplicationScoped, @Singleton, @RequestScoped, @Dependent) are beans. A class with only @Inject fields but no scope annotation is not a bean unless you configure otherwise.
  • Private members work but cost reflection. Package-private is preferred. Private injection fields get reflective access, which matters for native images, so Quarkus may warn you.
  • Beans are discovered at build time from the index, and removed if unused (Build-Time Architecture).
  • Programmatic lookup is available with Instance<T>:
Java
@Inject
Instance<Notifier> notifiers;

void sendToAll(String message) {
    for (Notifier n : notifiers) {   // iterates all matching beans
        n.notify(message);
    }
}

Instance<T> solves "I want every implementation", and also lets you check isResolvable() before calling get().

Do not create a bean with new and expect injection. new PriceService() gives you an object whose @Inject fields are null. Always obtain beans from the container, by injection.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does CDI decide which bean to inject?

    Resolution is type-based. If the type matches exactly one bean it is injected; qualifiers narrow the match further.
  2. 2. What happens when two beans match an injection point and nothing distinguishes them?

    ArC validates injection points at build time and reports ambiguous or unsatisfied dependencies before the app runs.
  3. 3. Which is true about constructor injection in Quarkus?

    Quarkus lets you skip @Inject when the bean has exactly one constructor.
  4. 4. Why is new PriceService() a bad idea inside a bean?

    Only the container wires injection points. An object created with new is just a plain object.
  5. 5. Which type lets you work with all beans of a type programmatically?

    Instance<T> is iterable and supports get(), isResolvable() and select() for programmatic lookup.

Summary

  • A bean is an object managed by the CDI container; a scope annotation such as @ApplicationScoped declares one.
  • Inject with fields (package-private), constructors (@Inject optional with one constructor) or setters.
  • Resolution is by type; unsatisfied and ambiguous dependencies are reported at build time.
  • Instance<T> gives programmatic access to many or optional beans.
  • Never create beans with new; ask the container.

Next: Bean Scopes