2 Replies Latest reply on Jul 6, 2014 4:54 AM by ericjvandervelden

    Can you inject in produced object in CDI?

    ericjvandervelden

      Suppose I have,

       

          public class Ctrl{

                  @Named @Produces public My getMy(){ return new My(); }

       

      I can use EL expressions referencing `my`.. So that's OK.

       

       

      But in the `My` type itself, I cannot inject, for example,

       

      public class My

              @Inject @Random private int randomNumber;

       

       

      The `randomNumber` field in `my` above is `null`.

       

       

      So my question is: Can you indeed not inject in a produced object, or am I doing something wrong?

        • 1. Re: Can you inject in produced object in CDI?
          mkouba

          Hi Eric,

          a producer method is fully responsible for creating a new instance of a an object. In other words, the CDI container only takes the result of the producer method. However, a producer method may have any number of parameters and all those parameters are injection points.

           

          So one way you could solve this:

          @Named
          @Produces
          public My getMy(@Random int randomNumber){ return new My(randomNumber); }
          

          The other way would be to use the CDI SPI to create an unmanaged instance. But I'm not so sure this makes much sense. I mean, what is the reason to use a producer then?

          • 2. Re: Can you inject in produced object in CDI?
            ericjvandervelden

            Thank you very much.