Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 119 ยท Servlets and JSP

CDI and Enterprise JavaBeans

Learn Jakarta CDI and EJB - dependency injection scopes, qualifiers, producers, interceptors, session beans, container-managed transactions and rollback rules, and how Spring compares.

Every Jakarta EE application needs two things from its server: a way to wire objects together and a way to run business code inside transactions. The platform answers with two specifications. CDI (Contexts and Dependency Injection, jakarta.enterprise and jakarta.inject) is the injection container, comparable to Spring's application context. EJB (Enterprise JavaBeans, jakarta.ejb) is the older component model whose beans are pooled, transactional and remotely callable. They overlap on purpose: CDI is the modern core, and EJB survives mostly in legacy systems and for a few special features.

In this lesson you will learn how CDI decides what to inject, what scopes and producers do, what interceptors are, how session beans differ, and exactly how container-managed transactions commit and roll back. No application server runs in this course's code runner, so real annotations appear in read-only snippets, while two runnable stand-ins written in plain Java reproduce what the container does: one resolves injection points and scopes with reflection, the other wraps methods in a transaction with a dynamic proxy and a real H2 database.

Beans and injection in CDI

In CDI almost any class is a bean. A bean is created by the container, and anything it needs is delivered with @Inject:

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

@ApplicationScoped
public class CheckoutService {

    private final PaymentGateway gateway;
    private final Cart cart;

    @Inject                                   // constructor injection: preferred, makes testing easy
    public CheckoutService(PaymentGateway gateway, Cart cart) {
        this.gateway = gateway;
        this.cart = cart;
    }

    public Receipt checkout() { return gateway.pay(cart.total()); }
}

You can inject into a constructor, a field or a setter method, and CDI prefers constructors. Resolution is type-safe: the container looks for beans whose type matches the injection point. If no bean matches, the deployment fails with an unsatisfied dependency error; if several match, it fails with an ambiguous dependency error. That is a feature: wiring mistakes surface at startup, not at the first request. In the default "annotated" discovery mode a class becomes a bean when it carries a scope annotation, so adding one is the usual way to make a class injectable.

Scopes decide the lifetime

A scope says how long an instance lives and who shares it.

Scope Lifetime Typical use
@Dependent (default) the same as the object it is injected into helpers, value objects
@RequestScoped one HTTP request request-bound state
@SessionScoped one HTTP session (must be Serializable) shopping cart, login state
@ApplicationScoped the whole application caches, configuration, shared services
@ConversationScoped a multi-request conversation you start and end wizards

For the normal scopes, what gets injected is not the instance but a client proxy. A request-scoped bean injected into an application-scoped bean still behaves correctly, because each method call goes through the proxy, which finds the instance of the current request. That is why scoped beans must be proxyable (non-final classes, a non-private no-argument constructor).

Qualifiers, producers and alternatives

When two beans implement the same interface, a qualifier tells CDI which one you want. A qualifier is just an annotation that you create:

Java
@Qualifier @Retention(RUNTIME) @Target({TYPE, FIELD, METHOD, PARAMETER})
public @interface Card { }

@Card @ApplicationScoped
public class CardGateway implements PaymentGateway { ... }

@Inject @Card PaymentGateway gateway;        // picks CardGateway

(@Named("card") is also a qualifier, mainly used so Jakarta Expression Language and JSF pages can refer to a bean by name.)

A producer method lets you create objects that are not simple beans: classes from libraries, values read from configuration, or instances that need custom setup. Its return type becomes an injectable type, and a matching @Disposes method cleans up.

Java
@ApplicationScoped
public class Resources {
    @Produces @ApplicationScoped
    HttpClient httpClient() {
        return HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
    }

    @Produces @Dependent
    Logger logger(InjectionPoint point) {                  // ask where it is injected
        return Logger.getLogger(point.getMember().getDeclaringClass().getName());
    }
}

Alternatives (@Alternative plus @Priority) replace a bean for a whole application, for example a fake payment gateway in tests. Events give you loose coupling: Event<OrderPlaced>.fire(...) on one side and void on(@Observes OrderPlaced e) on the other, with @ObservesAsync for asynchronous delivery.

The next program is a miniature CDI container. It scans fields marked @Inject, resolves them by type and qualifier, honors three scopes, and fails with the same two errors a real container reports at deployment:

Java A miniature CDI container

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 CheckoutService is created twice, because @Dependent means "new every time". The Cart is shared inside one request, and the AuditLog survives for the whole application. Real containers add client proxies and lazy creation, but resolution works as shown.

Interceptors: cross-cutting logic

An interceptor wraps business methods, as Spring AOP aspects do. You define an interceptor binding annotation, an interceptor class that handles it, and place the binding on the beans you want to wrap:

Java
@InterceptorBinding @Retention(RUNTIME) @Target({TYPE, METHOD})
public @interface Logged { }

@Logged @Interceptor @Priority(Interceptor.Priority.APPLICATION)
public class LoggingInterceptor {
    @AroundInvoke
    Object log(InvocationContext ctx) throws Exception {
        long start = System.nanoTime();
        try {
            return ctx.proceed();                              // call the real method
        } finally {
            System.out.println(ctx.getMethod().getName() + " took " + (System.nanoTime() - start) / 1_000_000 + " ms");
        }
    }
}

Jakarta Transactions uses exactly this mechanism for the @Transactional annotation, which you can put on any CDI bean. Decorators (@Decorator) are the sibling feature that wraps a specific interface rather than any method.

Session beans (EJB)

An enterprise bean is a managed component with services built in. The three kinds of session bean that matter:

Kind Annotation Instances Use
Stateless @Stateless pooled; any instance may serve any call services without client state
Stateful @Stateful one per client until @Remove or timeout conversational state
Singleton @Singleton one per application; @Lock(READ/WRITE) controls concurrency shared caches, startup tasks (@Startup)
Java
@Stateless
public class BankBean {
    @PersistenceContext EntityManager em;
    @EJB AuditBean audit;                                       // injection of another EJB

    public void transfer(long from, long to, BigDecimal amount) throws InsufficientFundsException {
        Account a = em.find(Account.class, from);
        if (a.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(from);
        a.withdraw(amount);
        em.find(Account.class, to).deposit(amount);
        audit.record(from, to, amount);
    }
}

EJBs offer things CDI beans do not: instance pooling, remote invocation (@Remote interfaces), timers (@Schedule(hour = "2")), @Asynchronous methods and container-managed security (@RolesAllowed). A bean is found by its JNDI name such as java:global/shop/BankBean, which a later lesson on JNDI explains. Jakarta EE has been shifting these features to CDI and separate specifications (Jakarta Concurrency, Jakarta Security), so for new code the advice is: use CDI beans, add @Transactional for transactions, and reach for EJB only when you need pooling, remoting or an existing codebase requires it.

Container-managed transactions

The most valuable EJB service is that the container starts and ends transactions around your business methods. Each method runs with a transaction attribute; the default is REQUIRED:

Attribute Behavior
REQUIRED (default) join the caller's transaction, or start a new one
REQUIRES_NEW always start a new one, suspending the caller's
MANDATORY the caller must have one, otherwise an exception
SUPPORTS use one if it exists, otherwise run without
NOT_SUPPORTED suspend the caller's transaction
NEVER fail if a transaction exists

When the method returns normally the container commits. When it throws, the kind of exception decides:

  • A system exception (any RuntimeException, or an Error) rolls the transaction back, and the container discards the bean instance.
  • An application exception (a checked exception) does not roll back by default, because it is treated as a business outcome the caller may handle. Annotate it @ApplicationException(rollback = true) to roll back, or call ctx.setRollbackOnly().

This is the same rule Spring's @Transactional follows (see Spring Transactions): runtime exceptions roll back, checked ones commit by default, and it surprises many developers. The stand-in below implements it with a java.lang.reflect.Proxy, JDBC and an in-memory H2 database, so you can watch the balances change or stay put:

Java A container that commits and rolls back

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 overdraft throws a checked exception marked rollback = true, so the debit is undone. The runtime bug rolls back by the system-exception rule. The note exception is a plain application exception, so the transfer commits, even though the method "failed". When you design exceptions for transactional code, decide on purpose which outcome you want.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens at deployment if two beans match an injection point and there is no qualifier?

    CDI resolution is type-safe and strict. Ambiguity is an error you fix with a qualifier, not something the container guesses.
  2. 2. Why can a @RequestScoped bean be injected into an @ApplicationScoped bean?

    Normal-scoped beans are injected as contextual proxies, so each method call reaches the instance belonging to the current context.
  3. 3. A stateless session bean method throws a checked exception that has no @ApplicationException annotation. What does the container do?

    Checked exceptions are application exceptions and do not roll back unless you ask for it with rollback = true or setRollbackOnly().
  4. 4. Which transaction attribute always starts a new transaction and suspends the caller's?

    REQUIRES_NEW is used for work that must commit independently, such as an audit record that must survive the outer rollback.
  5. 5. What is a producer method for?

    The return type of a @Produces method becomes an injectable type, which suits objects you cannot annotate or that need custom construction.

Summary

  • CDI is the injection container of Jakarta EE: type-safe resolution with @Inject, qualifiers for disambiguation, and failures at deployment, not at runtime.
  • Scopes (@Dependent, @RequestScoped, @SessionScoped, @ApplicationScoped) set lifetimes; normal-scoped beans are injected as client proxies.
  • Producers create non-bean objects, alternatives swap implementations, events decouple code, and interceptors add cross-cutting behavior.
  • EJB session beans (@Stateless, @Stateful, @Singleton) add pooling, remoting, timers and security; new code usually prefers CDI plus @Transactional.
  • Container-managed transactions default to REQUIRED; runtime exceptions roll back, checked exceptions commit unless marked rollback = true.

Next: SOAP Web Services and JAX-WS covers the XML-based service style that EJBs and servers also expose.