Auxiliary Tools :: Introduction to Contexts and Dependency Injection (CDI) – Part II – Producers


in progress

Producer Method
A producer method is a method that acts as a source of bean instances. When no instance exists in the specified context, the method declaration itself describes the bean, and the container invokes the method to obtain an instance of the bean. A producer method lets the application take full control of the bean instantiation process.
A producer exposes any sort of :

  • Class : unrestricted set of bean types, superclass, and all interfaces it implements directly or indirectly
  • Interface : unrestricted set of bean types, interfaces it extends directly or indirectly, and java.lang.Object
  • Primitive and Java array type

The simplest case

Here we have one interface (IBank), one implementation (BankOfAmerica), and a simple producer method:

Now, if we try to inject a bank bean like:


our container will not be able to decide to return correct implementation of IBank bean and will throw a Ambiguous dependencies error.

To solve the problem we create a qualifier called @QBankOfAmerica:


  • If a Producer bean has qualifier @QBankOfAmerica then container will call the GenericProducer method.
  • If a Producer bean has not a qualifier then container will inject directly the BankOfAmerica bean.

pom.xml for this example:


Multiple bean implementations – Polymorphism

Now we have more than one IBank implementation. Assume we have also HSBC and Chase.

Additionally, lets define a java annotation and an Enum to separate our IBank implementations in their injection points.

GenericProducer method have two parameters: Instance and InjectionPoint.


When we run example the output will be:

Withdrawal from Bank of America
Withdrawal from Chase
Withdrawal from HSBC


Leave a Reply