SeamFramework.orgCommunity Documentation

Chapter 4. Dependency injection and programmatic lookup

4.1. Injection points
4.2. What gets injected
4.3. Qualifier annotations
4.4. The built-in qualifiers @Default and @Any
4.5. Qualifiers with members
4.6. Multiple qualifiers
4.7. Alternatives
4.8. Fixing unsatisfied and ambiguous dependencies
4.9. Client proxies
4.10. Obtaining a contextual instance by programmatic lookup
4.11. The InjectionPoint object

One of the most significant features of CDI—certainly the most recognized—is dependency injection; excuse me, typesafe dependency injection.

The @Inject annotation lets us define an injection point that is injected during bean instantiation. Injection can occur via three different mechanisms.

Bean constructor parameter injection:

public class Checkout {

   private final ShoppingCart cart;
   public Checkout(ShoppingCart cart) {
      this.cart = cart;

Initializer method parameter injection:

public class Checkout {

   private ShoppingCart cart;
   void setShoppingCart(ShoppingCart cart) {
      this.cart = cart;

And direct field injection:

public class Checkout {

   private @Inject ShoppingCart cart;

Dependency injection always occurs when the bean instance is first instantiated by the container. Simplifying just a little, things happen in this order:

(The only complication is that the container might call initializer methods declared by a superclass before initializing injected fields declared by a subclass.)

CDI also supports parameter injection for some other methods that are invoked by the container. For instance, parameter injection is supported for producer methods:

@Produces Checkout createCheckout(ShoppingCart cart) {

    return new Checkout(cart);

This is a case where the @Inject annotation is not required at the injection point. The same is true for observer methods (which we'll meet in Chapter 11, Events) and disposer methods.

The CDI specification defines a procedure, called typesafe resolution, that the container follows when identifying the bean to inject to an injection point. This algorithm looks complex at first, but once you understand it, it's really quite intuitive. Typesafe resolution is performed at system initialization time, which means that the container will inform the developer immediately if a bean's dependencies cannot be satisfied.

The purpose of this algorithm is to allow multiple beans to implement the same bean type and either:

Obviously, if you have exactly one bean of a given type, and an injection point with that same type, then bean A is going to go into slot A. That's the simplest possible scenario. When you first start your application, you'll likely have lots of those.

But then, things start to get complicated. Let's explore how the container determines which bean to inject in more advanced cases. We'll start by taking a closer look at qualifiers.

If we have more than one bean that implements a particular bean type, the injection point can specify exactly which bean should be injected using a qualifier annotation. For example, there might be two implementations of PaymentProcessor:


public class SynchronousPaymentProcessor implements PaymentProcessor {
   public void process(Payment payment) { ... }

public class AsynchronousPaymentProcessor implements PaymentProcessor {
   public void process(Payment payment) { ... }

Where @Synchronous and @Asynchronous are qualifier annotations:


public @interface Synchronous {}

public @interface Asynchronous {}

A client bean developer uses the qualifier annotation to specify exactly which bean should be injected.

Using field injection:

@Inject @Synchronous PaymentProcessor syncPaymentProcessor;

@Inject @Asynchronous PaymentProcessor asyncPaymentProcessor;

Using initializer method injection:


public void setPaymentProcessors(@Synchronous PaymentProcessor syncPaymentProcessor, 
                                 @Asynchronous PaymentProcessor asyncPaymentProcessor) {
   this.syncPaymentProcessor = syncPaymentProcessor;
   this.asyncPaymentProcessor = asyncPaymentProcessor;

Using constructor injection:


public Checkout(@Synchronous PaymentProcessor syncPaymentProcessor, 
                @Asynchronous PaymentProcessor asyncPaymentProcessor) {
   this.syncPaymentProcessor = syncPaymentProcessor;
   this.asyncPaymentProcessor = asyncPaymentProcessor;

Qualifier annotations can also qualify method arguments of producer, disposer and observer methods. Combining qualified arguments with producer methods is a good way to have an implementation of a bean type selected at runtime based on the state of the system:


PaymentProcessor getPaymentProcessor(@Synchronous PaymentProcessor syncPaymentProcessor,
                                     @Asynchronous PaymentProcessor asyncPaymentProcessor) {
   return isSynchronous() ? syncPaymentProcessor : asyncPaymentProcessor;

If an injected field or a parameter of a bean constructor or initializer method is not explicitly annotated with a qualifier, the default qualifier, @Default, is assumed.

Now, you may be thinking, "What's the different between using a qualifier and just specifying the exact implementation class you want?" It's important to understand that a qualifier is like an extension of the interface. It does not create a direct dependency to any particular implementation. There may be multiple alterative implementations of @Asynchronous PaymentProcessor!

Whenever a bean or injection point does not explicitly declare a qualifier, the container assumes the qualifier @Default. From time to time, you'll need to decare an injection point without specifying a qualifier. There's a qualifier for that too. All beans have the qualifier @Any. Therefore, by explicitly specifying @Any at an injection point, you suppress the default qualifier, without otherwise restricting the beans that are eligible for injection.

Java annotations can have members. We can use annotation members to further discriminate a qualifier. This prevents a potential explosion of new annotations. For example, instead of creating several qualifiers representing different payment methods, we could aggregate them into a single annotation with a member:


public @interface PayBy {
   PaymentMethod value();

Then we select one of the possible member values when appling the qualifier:

private @Inject @PayBy(CHECK) PaymentProcessor checkPayment;

We can force the container to ignore a member of a qualifier type by annotating the member @Nonbinding.


public @interface PayBy {
   PaymentMethod value();
   @Nonbinding String comment() default "";

An injection point may specify multiple qualifiers:

@Inject @Synchronous @Reliable PaymentProcessor syncPaymentProcessor;

Then only a bean which has both qualifier annotations would be eligible for injection.

@Synchronous @Reliable

public class SynchronousReliablePaymentProcessor implements PaymentProcessor {
   public void process(Payment payment) { ... }

Alternatives are beans whose implementation is specific to a particular client module or deployment scenario. This alternative defines a mock implementation of both @Synchronous PaymentProcessor and @Asynchronous PaymentProcessor, all in one:

@Alternative @Synchronous @Asynchronous

public class MockPaymentProcessor implements PaymentProcessor {
   public void process(Payment payment) { ... }

By default, @Alternative beans are disabled. We need to enable an alternative in the beans.xml descriptor of a bean archive to make it available for instantiation and injection. This activation only applies to the beans in that archive.


When an ambiguous dependency exists at an injection point, the container attempts to resolve the ambiguity by looking for an enabled alternative among the beans that could be injected. If there is exactly one enabled alternative, that's the bean that will be injected.

The typesafe resolution algorithm fails when, after considering the qualifier annotations on all beans that implement the bean type of an injection point and filtering out disabled beans (@Alternative beans which are not explicitly enabled), the container is unable to identify exactly one bean to inject. The container will abort deployment, informing us of the unsatisfied or ambiguous dependency.

During the course of your development, you're going to encounter this situation. Let's learn how to resolve it.

To fix an unsatisfied dependency, either:

To fix an ambiguous dependency, either:

See this FAQ for step-by-step instructions for how to resolve an ambigous resolution exception between a raw bean type and a producer method that returns the same bean type.


Just remember: "There can be only one."

On the other hand, if you really do have an optional or multivalued injection point, you should change the type of your injection point to Instance, as we'll see in Section 4.10, “Obtaining a contextual instance by programmatic lookup”.

Now there's one more issue you need to be aware of when using the dependency injection service.

Clients of an injected bean do not usually hold a direct reference to a bean instance, unless the bean is a dependent object (scope @Dependent).

Imagine that a bean bound to the application scope held a direct reference to a bean bound to the request scope. The application-scoped bean is shared between many different requests. However, each request should see a different instance of the request scoped bean—the current one!

Now imagine that a bean bound to the session scope holds a direct reference to a bean bound to the application scope. From time to time, the session context is serialized to disk in order to use memory more efficiently. However, the application scoped bean instance should not be serialized along with the session scoped bean! It can get that reference any time. No need to hoard it!

Therefore, unless a bean has the default scope @Dependent, the container must indirect all injected references to the bean through a proxy object. This client proxy is responsible for ensuring that the bean instance that receives a method invocation is the instance that is associated with the current context. The client proxy also allows beans bound to contexts such as the session context to be serialized to disk without recursively serializing other injected beans.

Unfortunately, due to limitations of the Java language, some Java types cannot be proxied by the container. If an injection point declared with one of these types resolves to a bean with any scope other than @Dependent, the container will abort deployment, informing us of the problem.

The following Java types cannot be proxied by the container:

It's usually very easy to fix an unproxyable dependency problem. If an injection point of type X results in an unproxyable dependency, simply:

In certain situations, injection is not the most convenient way to obtain a contextual reference. For example, it may not be used when:

In these situations, the application may obtain an instance of the interface Instance, parameterized for the bean type, by injection:

@Inject Instance<PaymentProcessor> paymentProcessorSource;

The get() method of Instance produces a contextual instance of the bean.

PaymentProcessor p = paymentProcessorSource.get();

Qualifiers can be specified in one of two ways:

Specifying the qualifiers at the injection point is much, much easier:

@Inject @Asynchronous Instance<PaymentProcessor> paymentProcessorSource;

Now, the PaymentProcessor returned by get() will have the qualifier @Asynchronous.

Alternatively, we can specify the qualifier dynamically. First, we add the @Any qualifier to the injection point, to suppress the default qualifier. (All beans have the qualifier @Any.)

@Inject @Any Instance<PaymentProcessor> paymentProcessorSource;

Next, we need to obtain an instance of our qualifier type. Since annotatons are interfaces, we can't just write new Asynchronous(). It's also quite tedious to create a concrete implementation of an annotation type from scratch. Instead, CDI lets us obtain a qualifier instance by subclassing the helper class AnnotationLiteral.

abstract class AsynchronousQualifier

extends AnnotationLiteral<Asynchronous> implements Asynchronous {}

In some cases, we can use an anonymous class:

PaymentProcessor p = paymentProcessorSource

   .select(new AnnotationLiteral<Asynchronous>() {});

Now, finally, we can pass the qualifier to the select() method of Instance.

Annotation qualifier = synchronously ?
      new SynchronousQualifier() : new AsynchronousQualifier();
PaymentProcessor p =;

There are certain kinds of dependent objects (beans with scope @Dependent) that need to know something about the object or injection point into which they are injected in order to be able to do what they do. For example:

A bean with scope @Dependent may inject an instance of InjectionPoint and access metadata relating to the injection point to which it belongs.

Let's look at an example. The following code is verbose, and vulnerable to refactoring problems:

Logger log = Logger.getLogger(MyClass.class.getName());

This clever little producer method lets you inject a JDK Logger without explicitly specifying the log category:

class LogFactory {

   @Produces Logger createLogger(InjectionPoint injectionPoint) { 
      return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); 

We can now write:

@Inject Logger log;

Not convinced? Then here's a second example. To inject HTTP parameters, we need to define a qualifier type:


public @interface HttpParam {
   @Nonbinding public String value();

We would use this qualifier type at injection points as follows:

@HttpParam("username") String username;

@HttpParam("password") String password;

The following producer method does the work:

class HttpParams

   @Produces @HttpParam("")
   String getParamValue(ServletRequest request, InjectionPoint ip) {
      return request.getParameter(ip.getAnnotated().getAnnotation(HttpParam.class).value());

(Note that the value() member of the HttpParam annotation is ignored by the container since it is annotated @Nonbinding.)

The container provides a built-in bean that implements the InjectionPoint interface:

public interface InjectionPoint { 

   public Type getType();
   public Set<Annotation> getQualifiers();
   public Bean<?> getBean();
   public Member getMember();
   public Annotated getAnnotated();
   public boolean isDelegate();
   public boolean isTransient();