Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Dependency Injection and CDI

Bean Scopes in Quarkus

Learn how Quarkus CDI scopes control bean lifetime: @ApplicationScoped, @Singleton, @RequestScoped, @Dependent, client proxies, lazy creation and common pitfalls.

A scope answers the question "how long does this object live, and who shares it?" With @ApplicationScoped there is one shared instance for the whole application. With @RequestScoped there is a new instance for every HTTP request. The scope you choose affects memory, thread safety and even whether state leaks between users.

In this lesson you will learn the five scopes you use in Quarkus, what a client proxy is and why it matters, when beans are created (lazily or eagerly) and the mistakes that cause bugs. The real annotations are read-only. The two runnable examples are plain-Java stand-ins that count instances and model proxies.

The scopes at a glance

Scope Instances Client proxy Typical use
@ApplicationScoped One per application Yes Services, repositories, caches
@Singleton One per application No Same as above, slightly faster, no proxy
@RequestScoped One per HTTP request (or other request context) Yes Per-request data such as the current user
@Dependent One per injection point No Small helpers; the default when no scope is given on a producer
@SessionScoped One per HTTP session Yes Rare; needs the undertow extension and breaks statelessness

@ApplicationScoped, @Singleton, @RequestScoped and @Dependent cover nearly everything. In Quarkus REST resources are @Singleton by default (one resource instance), which is why you should not keep per-request state in resource fields.

Java
@ApplicationScoped
public class CatalogService { /* shared, stateless service */ }

@Singleton
public class Clock { /* shared, no proxy */ }

@RequestScoped
public class CurrentUser {
    String name;      // different for every request
}

@Dependent
public class Formatter { /* a new one for every injection point */ }

Choosing a scope

ApplicationScoped One shared service. Start here.
Singleton One instance, no proxy.
RequestScoped A fresh object for each request.
Dependent A new object for each injection.

Shared beans must be thread safe.

1 / 2

Client proxies

@ApplicationScoped and @RequestScoped are normal scopes. When you inject such a bean, you do not receive the bean itself but a client proxy: a small generated subclass that forwards each method call to the current instance in the right context. That is how a long-lived singleton can hold a reference to a @RequestScoped bean: the proxy looks up the request's instance on every call.

Java
@ApplicationScoped
public class AuditService {

    @Inject
    CurrentUser user;         // a proxy, not a real CurrentUser

    public void log(String action) {
        // user.name resolves against the CURRENT request each time
    }
}

Two consequences matter:

  1. Laziness. For @ApplicationScoped, the real instance is created the first time a method is called through the proxy, not when the proxy is injected. If you need eager creation, observe the startup event or annotate the class with @Startup (Events and Lifecycle).
  2. Proxy limitations. A client proxy is a subclass, so the bean class must not be final, and public methods must not be final. Quarkus can transform these for you in many cases (quarkus.arc.transform-unproxyable-classes=true, the default), but avoid final on bean classes.

@Singleton skips the proxy: the injected reference is the real object, created when first needed (also lazily unless you use @Startup). That makes @Singleton a touch faster and the reference identity simpler, but QuarkusMock can only replace normal-scoped beans, so @ApplicationScoped is friendlier to tests. Most teams use @ApplicationScoped as the standard and keep @Singleton for simple holders.

Counting instances

The first stand-in simulates the container's scope handling. It hands out instances according to a scope and counts how many were created. Run it and match each count to the table above.

Java Stand-in: how many instances does each scope create?

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.

The result: APPLICATION creates one object for 6 injections; REQUEST creates one per request (two); DEPENDENT creates a new one every time (six). Keep that picture in mind when you think about memory and sharing.

Thread safety

Because @ApplicationScoped and @Singleton beans are shared by all request threads at once, their state must be thread safe. These are the common patterns:

  • Stateless services. No mutable fields. This is the best choice and the most frequent.
  • Immutable state. Fields set once in the constructor and never changed.
  • Thread-safe state. ConcurrentHashMap, AtomicLong, LongAdder or explicit locks.
Java
@ApplicationScoped
public class VisitCounter {
    private final AtomicLong visits = new AtomicLong();

    public long hit() {
        return visits.incrementAndGet();
    }
}

A private int visits with visits++ would lose updates under concurrent requests. Per-user or per-request state must not live in an application-scoped bean. Use method parameters, a @RequestScoped bean or a database.

Request scope outside HTTP

A request context exists for each HTTP request. Quarkus also activates one for scheduled method invocations, message consumers and @QuarkusTest methods. In a plain thread you started yourself, there is no active request context, and using a @RequestScoped bean there throws ContextNotActiveException. In that case activate it with @ActivateRequestContext on a method of a bean:

Java
import jakarta.enterprise.context.control.ActivateRequestContext;

@ApplicationScoped
public class Worker {

    @ActivateRequestContext
    public void runInBackground() {
        // request-scoped beans may be used here
    }
}

A proxy stand-in

The second stand-in recreates a lazy client proxy using java.lang.reflect.Proxy. The proxy is injected immediately but the real object is built only when the first method call arrives, exactly the behaviour of an @ApplicationScoped bean.

Java Stand-in: a lazy client proxy

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.

The real greeter is built on the first call, and the second call reuses it. The proxy also explains an error message you will meet: if a bean cannot be subclassed (a final class), Quarkus cannot create its proxy and reports an unproxyable bean type.

Choosing and avoiding mistakes

  1. Default to @ApplicationScoped for services and repositories.
  2. Do not store request data in application-scoped fields. This causes data leaks between users.
  3. Do not call new on beans, and do not inject a @Dependent bean into a long-lived bean thinking it refreshes: it is created once for that injection point, so it lives as long as its owner.
  4. Remember that a bean never used may be removed; see Build-Time Architecture.
  5. For true lazy and optional access, inject Instance<T>, which looks up a fresh instance on each get() for a @Dependent type.

Quarkus 3 uses jakarta.enterprise.context.* and jakarta.inject.Singleton. The javax packages from older articles will not compile.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which scope gives a new bean instance for every HTTP request?

    @RequestScoped ties the instance to the current request context and discards it afterwards.
  2. 2. What do you inject when a bean is @ApplicationScoped?

    Normal-scoped beans are injected as client proxies, which also makes lazy creation possible.
  3. 3. What is the main thread-safety rule for @ApplicationScoped beans?

    Many request threads call the same instance at once, so unsynchronised mutable fields cause lost updates.
  4. 4. What happens if you use a @RequestScoped bean in a thread you created yourself without a request context?

    There is no active request context in your own threads. Use @ActivateRequestContext on a bean method to create one.

Summary

  • @ApplicationScoped (shared, proxied) is the default for services; @Singleton is shared without a proxy.
  • @RequestScoped is per request; @Dependent is per injection point.
  • Normal-scoped beans are injected as client proxies, created lazily on first use.
  • Shared beans must be stateless, immutable or thread safe.
  • Request scope needs an active request context; use @ActivateRequestContext outside HTTP.

Next: Qualifiers and Producers