Return to site

💉⚙️ CDI ALTERNATIVES: WHICH IMPLEMENTATION GETS INJECTED?

· jakartaee

🔸 TLDR

▪️ If an @Alternative is enabled in beans.xml, CDI will inject that alternative for matching injection points. 🔁

Section image

🔸 CONTEXT

You have one interface and two CDI beans that implement it:

a “normal/default” handler ✅

an @Alternative handler 🔁 (disabled unless explicitly enabled)

Then you enable the alternative in beans.xml, and you inject the interface type.

🔸 QUESTION 🧠

Imagine this setup (simplified):

✅ What will messageHandler reference at runtime?

🔸 OPTIONS

▪️ SmsHandler

▪️ MsgHandler

▪️ None (ambiguous injection error)

▪️ GenericMessenger

🔸 ANSWER ✅

▪️ SmsHandler

Because SmsHandler is marked @Alternative and it is activated in beans.xml, CDI will use it as the selected implementation for that injection point. In practice, this is exactly why alternatives exist: swap implementations at deployment time without changing code.

🔸 TAKEAWAYS ✅

▪️ @Alternative does nothing by itself → it must be enabled (via beans.xml or @Priority).

▪️ Alternatives are a clean way to switch implementations per environment (prod vs staging, real vs stub, etc.). 🧩

▪️ If you truly want multiple implementations side-by-side, use custom qualifiers (not alternatives). 🎯

#JakartaEE #CDI #DependencyInjection #Java #BeansXML #Weld #EnterpriseJava #SoftwareArchitecture #Testing #MicroProfile

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇