1 Reply Latest reply on Jul 22, 2019 4:17 AM by manovotn

    When should one use createCreationalContext(null) and/or createCreationalContext(bean)?

    ljnelson

      Suppose I get my hands on a Bean via successful bean resolution:

       

      final Bean<?> bean = beanManager.resolve(someBeans);

       

      Now I want to programmatically get a contextual reference for it.

       

      I have done this sort of thing many, many times over the years.  But I've never been clear on the creation of the CreationalContext argument.

       

      In general, should I do:

       

      beanManager.getReference(bean, whateverType, beanManager.createCreationalContext(bean));

       

      …or do I do:

       

      beanManager.getReference(bean, whateverType, beanManager.createCreationalContext(null));

       

      …?

       

      My mental model is that the CreationalContext is basically a Dependent-scoped object "holder" for the reference acquired.  So if my bean has dependent objects I would think I'd want the first form.  Is that mental model correct?

       

      My further understanding is that if I use the second form, I am basically saying, "I am not concerned, for better or for worse, with the lifecycle of any Dependent-scoped references that might be injected into the reference that I am about to acquire".

       

      Best,

      Laird

        • 1. Re: When should one use createCreationalContext(null) and/or createCreationalContext(bean)?
          manovotn

          Hi Laird,

           

          your "mental model" is very close, CreationalContext is indeed a "holder" that glues together a normal scoped bean with its Dependent dependencies. That way you know when to destroy those Dependent beans.

          Therefore, when operating with BM.getReference(...) you want to use the non-null variant so that dependent objects get destroyed properly.

           

          For the method BM.createCreationalContext() itself, in CDI spec this is chapter 11.3.5. Obtaining a CreationalContext.

          What it says it that for any contextual instance you should be using the non-null variant. That means for any class that is backed by a CDI bean; in short whenever you can supply that, do it.

           

          The other form with null is then used for non-contextual objects - e.g. whenever you want to create a CC for a class that doesn't have a bean backing it.

          What I can think of is for instance when enforcing CDI injection into a non-CDI object via BM.createInjectionTarget(...).inject(foo, null).