Search code examples
jakarta-eecdi

Do I need to destroy CreationalContext used in BeanManager.getReference?


There is something I do not understand with CreationalContext and BeanManager.getReference in CDI.

I'm using CDI 1.2 with Wildfly 8.2.1, and here is my problem.

I have a CDI bean which is produced by a third-party library.

The bean :

public class ProducedBean
{
   private long m_id;

   public long getId()
   {
      return m_id;
   }
}

And the producer (it's just an example):

@Produces
public ProducedBean getBean()
{
   return new ProducedBean();
}

In a CDI custom Scope context, I need to access this bean. So I use the BeanManager :

final Set<Bean<?>> beans = beanManager.getBeans(ProducedBean.class);
final Bean<?> bean = beanManager.resolve(beans);
CreationalContext<JobContext> creationalContext = beanManager.createCreationalContext(null);
final ProducedBean producedBean = (ProducedBean) beanManager.getReference(bean, ProducedBean.class, creationalContext);
// Get id of ProducedBean
// Then release creationalContext?

I have 2 questions regarding this code :

1°) Do I need to destroy the creationalContext after ProducedBean creation? I read the javadoc but it is not clear to me. I just want to get the id of ProducedBean.

2°) Is it better to use beanManager.createCreationalContext(null) or beanManager.createCreationalContext(bean)? In my case I just read the id of ProducedBean.

Thanks.


Solution

  • First of all, your bean is (I hope intentionally) @Dependent which afflicts the way you need to handle it. For @Dependent you have one instance per injection and it is destroyed once you destroy the contextual bean which injected it. Therefore in your case, you will want to handle this manually.

    Now, to you specific questions:

    1. No need to handle the context itself. Instead, once you are done working with your ProducedBean go back to Bean<ProducedBean> object and make sure you call its destroy(T instance, CreationalContext<T> creationalContext) method. Again, you need to do this, because your bean is @Dependent.
    2. You will most likely want to use beanManager.createCreationalContext(bean). The reason being that if your ProducedBean has any (contextual) dependencies, e.g. injects other stuff, this will resolve the injections. With null, it is only good for unmanaged instanced if I recall correctly.