Monday, May 20, 2013

Contexts and Dependency Injection(CDI) - Producer


@Produces is a CDI mechanism which allows defining a source for injection. One can use Producer Method or Producer field to generate objects.


Here is brief explanation from JEE 6 tutorial:

A producer method generates an object that can then be injected. Typically, you use producer methods in the following situations:
  • When you want to inject an object that is not itself a bean
  • When the concrete type of the object to be injected may vary at runtime
  • When the object requires some custom initialization that the bean constructor does not perform
(Code snippet from attached Source)


A producer field is a simpler alternative to a producer method; it is a field of a bean that generates an object. It can be used instead of a simple getter method. Producer fields are particularly useful for declaring Java EE resources such as data sources, JMS resources, and web service references.

(Code snippet from attached Source)

This is how an Object in Injected

(Code snippet from attached Source)


This example shows both ways of declaring a producer and Injection.

Click here to download source code


Prasanna Bhale

1 comment: