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;
    
   @Inject
   public Checkout(ShoppingCart cart) {
      this.cart = cart;
   }
}

A bean can only have one injectable constructor.

Initializer method parameter injection:

public class Checkout {

        
   private ShoppingCart cart;
   @Inject
   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:

@Synchronous

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

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

Where @Synchronous and @Asynchronous are qualifier annotations:

@Qualifier

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

@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
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:

@Inject

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

Using constructor injection:

@Inject

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:

@Produces

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 alternative 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 declare 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.

This is especially useful if you want to iterate over all beans with a certain bean type. For example:

@Inject 

void initServices(@Any Instance<Service> services) { 
   for (Service service: services) {
      service.init();
   }
}

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:

@Qualifier

@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface PayBy {
   PaymentMethod value();
}

Then we select one of the possible member values when applying 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.

@Qualifier

@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
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.


<beans
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
   <alternatives>
         <class>org.mycompany.mock.MockPaymentProcessor</class>
   </alternatives>
</beans>

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 ambiguous 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 annotations 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>() {});

However, we can't use an anonymous class to implement a qualifier type with members.

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

Annotation qualifier = synchronously ?
      new SynchronousQualifier() : new AsynchronousQualifier();
PaymentProcessor p = anyPaymentProcessor.select(qualifier).get().process(payment);

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:

@BindingType

@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
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(InjectionPoint ip) {
      ServletRequest request = (ServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
      return request.getParameter(ip.getAnnotated().getAnnotation(HttpParam.class).value());
   }
}

Note that acquiring of the request in this example is JSF-centric. For a more generic solution you could write your own producer for the request and have it injected as a method parameter.

Note also 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();
}