Search code examples
javacdijava-ee-7

Do we need to destroy a CDI bean obtained programmatically?


I have obtained a CDI bean which was obtained programatically using the following code:

MyBean bean = CDI.current().select(MyBean.class, qualifier).get();

Once I am done, do I need to destroy this bean using

CDI.current().destroy (bean);

Or does the bean inherit the scope from my class?


Solution

  • Or does the bean inherit the scope from my class?

    Definitely no. It will have whatever scope you gave to MyBean.

    do I need to destroy this bean

    If your bean is normal scoped you don't need to do that. If, however, it is so called pseudo-scope, you might need to destroy it. For the record, normal scoped are all basic CDI scopes except for @Dependent.

    The reason is that @Dependent lifecycle (so destroy as well) is bound to a bean where you inject it. But you didn't really inject it, instead you did programmatic lookup. Therefore, it isn't bound to any other bean and you should destroy it.