CDI and Jakarta REST
What you will learn
CDI manages contextual beans while Jakarta REST maps HTTP requests to resource methods. Keep HTTP transport separate from the business service.
- Trace a REST request into an injected service.
- Compare request and application scopes.
- Define stable success and missing-resource contracts.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Jakarta EE examples require the pinned companion Maven project or separately configured illustrative infrastructure. Their predicted results are not execution evidence.
Inject a test catalog
public class Main { interface Lookup {String find(String id);} record Resource(Lookup lookup){String get(String id){String title=lookup.find(id);return title==null?"404":"200 "+title;}} public static void main(String[] args) {var resource=new Resource(id -> "B1".equals(id)?"Java Basics":null);System.out.println(resource.get("B1"));System.out.println(resource.get("B2")); }}Expected output:
200 Java Basics404Manual injection models testable design, not CDI resolution or HTTP.
Injection and scope
CDI selects beans by type and qualifiers. Unsatisfied or ambiguous injection points are deployment problems, not null fallbacks. RequestScoped instances are associated with an active request context; ApplicationScoped is shared in an application and can be invoked concurrently. A normal-scoped reference may be a client proxy; do not rely on object identity or self-invocation to establish interception. A shared service must not keep mutable request-local data. @Inject is Jakarta Dependency Injection; CDI supplies discovery and contextual behavior. In the lab the resource has a bean-defining scope and receives an application-scoped service.
HTTP and serialization
@ApplicationPath adds an application prefix, @Path matches resource routes, @GET selects the verb, @PathParam binds a segment and @Produces advertises a representation. Response builds explicit status and entity. JSON-B binds Java objects to JSON; JSON-P provides JSON object/stream APIs without requiring a domain class. Return a DTO instead of a persistence entity. Compare fields rather than relying on JSON property order. Spring MVC uses analogous controller mappings and injected services, but lifecycle, error mappings, and bootstrap configuration are different. Contract testing on two certified products is needed for a portability claim.
Separate request state
public class Main { static class Catalog {String find(String id){return "item-"+id;}} record Request(Catalog service,String id){String result(){return service.find(id);}} public static void main(String[] args) {var service=new Catalog();var a=new Request(service,"B1");var b=new Request(service,"B2");System.out.println(a.result());System.out.println(b.result()); }}Expected output:
item-B1item-B2Immutable request data is separate from the shared stateless service.
CDI catalog service
Source-reviewed, NOT RUN. File lab-fixtures/jakarta-ee-v42/src/main/java/example/catalog/CatalogService.java; use the companion lab README.
package example.catalog;import jakarta.enterprise.context.ApplicationScoped;import java.util.Optional;@ApplicationScopedpublic class CatalogService { public Optional<BookView> find(String id) { return "B1".equals(id) ? Optional.of(new BookView("B1", "Java Basics")) : Optional.empty(); }}Predicted behavior: An injected service returns a known book or empty Optional.
No mutable per-request state in the shared service.
Jakarta REST resource
Source-reviewed, NOT RUN. File lab-fixtures/jakarta-ee-v42/src/main/java/example/catalog/CatalogResource.java; use the companion lab README.
package example.catalog;import jakarta.enterprise.context.RequestScoped;import jakarta.inject.Inject;import jakarta.ws.rs.*;import jakarta.ws.rs.core.*;@RequestScoped@Path("/books")@Produces(MediaType.APPLICATION_JSON)public class CatalogResource { @Inject CatalogService service; @GET @Path("/{id}") public Response find(@PathParam("id") String id) { return service.find(id).map(b -> Response.ok(b).build()) .orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); }}Predicted behavior: Known ID returns 200 JSON; unknown ID returns 404.
No real HTTP execution; BookView is a separate file in the WAR.
Common mistakes
Do not instantiate a resource manually and expect CDI to inject it, assume a shared bean is thread-safe automatically, or return 200 with null for missing items.
Practice
Implement a manually injected lookup returning 200 for B1 and 404 for anything else. Print statuses for B1, B9 and blank.
Expected output:
200404404Compare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CDI and Jakarta REST — knowledge check
Jakarta EE enterprise Java reasoning.
What should a shared service avoid?
What does @PathParam bind?
Which component provides JSON object and streaming APIs?
What status represents a missing book?
Does manually constructing a bean prove CDI injection?