CDI and ArC

CDI
Contexts and Dependency Injection

Mid-level Frequently asked 5 min

On this page

The question

What is the difference between @ApplicationScoped, @Singleton and @RequestScoped in Quarkus?

30-second answer

All three come from CDI. @ApplicationScoped gives one instance per app behind a client proxy, created on its first method call. @Singleton also gives one instance, with no proxy, so it is created when first injected. @RequestScoped gives one instance per HTTP request, behind a proxy, so an application-scoped bean can inject it safely. Prefer @ApplicationScoped unless you have a reason.

Understand it

CDI scopes against Spring scopes

Compare

In CDI, @ApplicationScoped gives one instance behind a client proxy, created on first use. @Singleton gives one with no proxy. With no scope declared, a bean is @Dependent.

View as text

Five rows: the default scope, one per app, one per app with no proxy, one per request, and new per injection. Each row shows the annotation that gives it and a badge saying whether a proxy or the instance itself is injected.

CDI in Quarkus: In CDI, @ApplicationScoped gives one instance behind a client proxy, created on first use. @Singleton gives one with no proxy. With no scope declared, a bean is @Dependent. Default scope: @Dependent, direct. One per app: @ApplicationScoped, proxy. One per app, no proxy: @Singleton, direct. One per request: @RequestScoped, proxy. New per injection: @Dependent, direct.

Spring: In Spring, a bean is a singleton unless you say otherwise, created at startup and injected directly. Only web scopes, such as request, inject a proxy. Default scope: singleton, direct. One per app: singleton, direct. One per app, no proxy: singleton, direct. One per request: @RequestScope, proxy. New per injection: @Scope("prototype"), direct.

Five rows: the default scope, one per app, one per app with no proxy, one per request, and new per injection. Each row shows the annotation that gives it and a badge saying whether a proxy or the instance itself is injected.

CDI in Quarkus: In CDI, @ApplicationScoped gives one instance behind a client proxy, created on first use. @Singleton gives one with no proxy. With no scope declared, a bean is @Dependent. Default scope: @Dependent, direct. One per app: @ApplicationScoped, proxy. One per app, no proxy: @Singleton, direct. One per request: @RequestScoped, proxy. New per injection: @Dependent, direct.

Spring: In Spring, a bean is a singleton unless you say otherwise, created at startup and injected directly. Only web scopes, such as request, inject a proxy. Default scope: singleton, direct. One per app: singleton, direct. One per app, no proxy: singleton, direct. One per request: @RequestScope, proxy. New per injection: @Scope("prototype"), direct.

Takeaway: CDI defaults to @Dependent and puts @ApplicationScoped beans behind a lazy client proxy. Spring defaults to a singleton created at startup and injected directly.

ArC resolves injection at build

Step by step

At build, ArC reads the Jandex index and finds five beans from their annotations: a REST resource, a service, two payment gateways and an audit log.

Step 1 of 7
View as text

A graph of five beans for a production build. OrderResource injects OrderService, which injects a PaymentGateway. StripeGateway and FakeGateway both implement it, and AuditLog stands alone. A mark under the graph says the outcome of each step.

At build, ArC reads the Jandex index and finds five beans from their annotations: a REST resource, a service, two payment gateways and an audit log.

Each injection point is matched by type and qualifiers. OrderService injects a PaymentGateway, and two beans implement that interface.

Two beans match one injection point, so the build fails with an ambiguous dependency error, before anything is packaged or deployed. Both gateway edges are drawn as failing.

FakeGateway gets @IfBuildProfile("test"), and StripeGateway @UnlessBuildProfile("test"). Each build keeps exactly one, so the match succeeds. FakeGateway is dimmed as test only.

Nothing injects AuditLog, so ArC removes it. A lookup by type at run time would find nothing; @Unremovable keeps it. AuditLog is dimmed as removed.

ArC generates a bean class, a factory and a client proxy for each bean, as plain bytecode. Nothing uses reflection to create or inject them. Each bean shows a generated badge.

At startup the generated code runs. OrderService is created on its first call through the proxy, already wired to StripeGateway. OrderService is marked created.

A graph of five beans for a production build. OrderResource injects OrderService, which injects a PaymentGateway. StripeGateway and FakeGateway both implement it, and AuditLog stands alone. A mark under the graph says the outcome of each step.

At build, ArC reads the Jandex index and finds five beans from their annotations: a REST resource, a service, two payment gateways and an audit log.

Each injection point is matched by type and qualifiers. OrderService injects a PaymentGateway, and two beans implement that interface.

Two beans match one injection point, so the build fails with an ambiguous dependency error, before anything is packaged or deployed. Both gateway edges are drawn as failing.

FakeGateway gets @IfBuildProfile("test"), and StripeGateway @UnlessBuildProfile("test"). Each build keeps exactly one, so the match succeeds. FakeGateway is dimmed as test only.

Nothing injects AuditLog, so ArC removes it. A lookup by type at run time would find nothing; @Unremovable keeps it. AuditLog is dimmed as removed.

ArC generates a bean class, a factory and a client proxy for each bean, as plain bytecode. Nothing uses reflection to create or inject them. Each bean shows a generated badge.

At startup the generated code runs. OrderService is created on its first call through the proxy, already wired to StripeGateway. OrderService is marked created.

Takeaway: ArC discovers beans, matches injection points, removes unused beans and generates the wiring as bytecode, all during the build. A wiring mistake fails the build, not production.

Which scope for which bean?One shared instance per app is ApplicationScoped, or Singleton when you want no proxy. One instance per HTTP request is RequestScoped. A new instance for every injection point is Dependent, the default.How manyinstances?One per app, shared:@ApplicationScopedOne per app, noproxy:@SingletonOne per request:@RequestScopedOne per injection:@Dependent, thedefault
Which scope for which bean?One shared instance per app is ApplicationScoped, or Singleton when you want no proxy. One instance per HTTP request is RequestScoped. A new instance for every injection point is Dependent, the default.How manyinstances?One per app, shared:@ApplicationScopedOne per app, noproxy:@SingletonOne per request:@RequestScopedOne per injection:@Dependent, thedefault
Which scope for which bean?

In code

@ApplicationScoped // one instance, behind a client proxy
public class OrderService {

    @Inject
    PaymentGateway gateway; // package-private: no reflection

    void pay(Order order) {
        gateway.charge(order.total());
    }
}

public interface PaymentGateway {
    void charge(BigDecimal amount);
}

@UnlessBuildProfile("test")
@ApplicationScoped
public class StripeGateway implements PaymentGateway {
    public void charge(BigDecimal amount) { }
}

@IfBuildProfile("test")
@ApplicationScoped
public class FakeGateway implements PaymentGateway {
    public void charge(BigDecimal amount) { }
}
Scopes, and a gateway chosen by build profile
@Unremovable
@ApplicationScoped
public class AuditLog {
    void record(String event) { }
}

class Auditing {
    void audit(String event) {
        CDI.current().select(AuditLog.class).get().record(event);
    }
}
Keep a bean that only a run-time lookup uses
Which gateway each build injectsOrderService injects a PaymentGateway. The production build keeps only StripeGateway, and the test build keeps only FakeGateway, so each build resolves exactly one bean.OrderService injectsPaymentGatewayprod build:StripeGatewaytest build:FakeGateway
Which gateway each build injectsOrderService injects a PaymentGateway. The production build keeps only StripeGateway, and the test build keeps only FakeGateway, so each build resolves exactly one bean.OrderService injectsPaymentGatewayprod build:StripeGatewaytest build:FakeGateway
Which gateway each build injects
@ApplicationScoped
class TimeConfig {
    @Produces
    @Singleton                                   // no client proxy needed for a JDK (Java Development Kit) type
    Clock clock() { return Clock.systemUTC(); }
}

@ApplicationScoped
class InvoiceService {
    @Inject Clock clock;                         // a test can produce a fixed Clock instead
}
A producer method makes a bean from a class you cannot annotate

Solve it

@ApplicationScoped or @Singleton for a heavy HTTP client?

A RatesClient opens a connection pool when it is created. One teammate wants @Singleton “because it is faster”, another wants @ApplicationScoped. Tests must replace it with @InjectMock. Decide and explain.

  1. Find what both share. Each gives one instance for the whole application. The difference is the client proxy.
  2. @ApplicationScoped. Injection points receive a proxy, and the instance is created on its first method call. Normal scopes like this one are what @InjectMock replaces.
  3. @Singleton. No proxy, so calls are direct and slightly cheaper, and the instance is created when first injected. @InjectMock needs extra configuration for it.
  4. Decide. The test requirement and the expensive constructor favor @ApplicationScoped: easy to mock, created only when used. Add @Startup only if it must be warm, knowing every test run then builds it too.
  5. Check. A @QuarkusTest with @InjectMock RatesClient passes, and no pool opens in tests that never call it.
@ApplicationScoped
class RatesClient {
    private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();
    BigDecimal rate(String currency) { /* call the rates API */ return BigDecimal.ONE; }
}

@QuarkusTest
class CheckoutTest {
    @InjectMock RatesClient rates;               // works because the scope is normal

    @Test
    void usesTheRate() { Mockito.when(rates.rate("EUR")).thenReturn(new BigDecimal("1.10")); }
}
Lazy and mockable

How to answer

  • A client proxy lets a long-lived bean reach the right instance, created only when needed.
  • @Singleton skips the proxy, so it is a little cheaper, but @InjectMock cannot replace it.
  • With no scope declared, a CDI bean is @Dependent, a new instance per injection point.
  • The Quarkus documentation recommends @ApplicationScoped as the default choice.

Common mistakes

  • Assuming CDI defaults to a singleton, as Spring does. The default scope is Dependent.
  • Saying Singleton and ApplicationScoped are the same. Only ApplicationScoped injects a client proxy.

Follow-up questions

What is a client proxy in CDI, and why does it exist?

A client proxy is what gets injected for a normal-scoped bean, such as @ApplicationScoped or @RequestScoped. It is a generated subclass that, on every call, finds the current instance in its context and delegates to it. This lets a long-lived bean hold a request-scoped one safely, makes creation lazy, and allows circular dependencies between normal-scoped beans.

  • ArC generates its proxies as bytecode during the build, with no reflection.
  • Each call pays a small lookup, which is why @Singleton exists.
  • Spring uses the same idea for request-scoped beans, with scoped proxies.

See it in the infographic: CDI scopes against Spring scopes See it in the infographic: ArC resolves injection at build

What does ArC do during the build that a runtime CDI container does at startup?

ArC reads the Jandex index, discovers beans, matches every injection point to exactly one bean, removes beans nothing uses, and generates bean classes, factories and client proxies as bytecode. An unsatisfied or ambiguous dependency fails the build. At startup, nothing is scanned and no reflection is needed; the generated code creates instances when they are first used.

  • Package-private injection fields avoid reflection; private ones need it.
  • ArC implements CDI Lite, so portable extensions are replaced by build compatible extensions.
  • Wiring errors surface during the build, before anything is deployed.

See it in the infographic: ArC resolves injection at build

A bean you only look up programmatically at run time is not found in Quarkus. Why?

ArC removes beans that nothing injects, observes or names, to save memory and startup time. A lookup such as CDI.current().select() happens at run time, so the build cannot see it and removes the bean. Mark the bean @Unremovable, inject it through Instance<T> somewhere, or list it in quarkus.arc.unremovable-types.

  • Beans with observer methods, REST (Representational State Transfer) endpoints and @Named beans are kept.
  • quarkus.arc.remove-unused-beans=none turns removal off, at a cost in memory and startup.
  • Removal is why a Quarkus app carries only the beans it really uses.

See it in the infographic: ArC resolves injection at build

Why can a final class be a problem for an @ApplicationScoped bean?

A client proxy is a generated subclass, so the bean class must not be final and needs a constructor the proxy can call. Quarkus relaxes this: by default it removes the final modifier and adds the missing constructor during the build, which a runtime container could not do.

Check yourself

1. Two beans each inject the same @Dependent bean. How many instances of it exist?
Show answers
  • Two, one per injection point: Correct. @Dependent creates a new instance for every bean that injects it.
  • One, shared by both: Incorrect. That is @ApplicationScoped or @Singleton, not @Dependent.
  • None until the first call: Incorrect. Lazy creation comes from a client proxy, and @Dependent beans have none.
2. Two beans implement PaymentGateway, and a service injects PaymentGateway with no qualifier. When does Quarkus report the problem?
Show answers
  • When the app is built: Correct. ArC resolves every injection point during the build, so the build fails.
  • When the app starts: Incorrect. A runtime container would find it at startup. ArC finds it earlier, during the build.
  • On the first call to the service: Incorrect. Only creating the instance is lazy. Resolution happened during the build.