CDI Producer

CDI (Context and dependency injection) is a great specification introduced in the JEE6 that offers a lot of resources. One of them is the Producer methods, and we’ll be talking about it in this post.

CDI Producer can be used in some scenarios, such as:

Making Non-CDI beans eligible to be injected into other CDI beans. You may be using some library that doesn’t expose their beans via CDI but you want to inject them in your CDI beans by convenience.

You have a bean that requires a constructor with some argument.

These are some scenarios where CDI Producer methods can be applied.

You can also watch the video below, where I show step-by-step the creation of the basic example and a few more details:

Basic example

Let’s see through a basic example how to use CDI Producer methods. Imagine that you have an interface and one implementation for this interface, but this implementation only provides a constructor that takes one argument. In this case, you cannot inject this class automatically in other CDI beans, as it doesn’t provide a default constructor.

That happens because there’s no implementation of the SimpleDao interface that is a CDI bean. In order to solve this issue, we can create a CDI producer method, responsible for creating an instance of FileSimpleDao that allows it to be injected in any CDI bean.

CDI Producer and scopes

You may be wondering when the instances of SimpleDao are created: one per application, per request..
Actually, you can use any CDI scope in your producer. It’s important to notice, however, that you should place the scope annotation in the producer method and not in the producer class. For example, if you want to make sure that only one instance of the bean is created, you need to annotate the producer method with @ApplicationScoped instead of using this annotation in the producer class.

So, that was a quick introduction to CDI producer and you can find the complete code here. You can also watch the video above, where I show everything working.