2 Replies Latest reply on Jul 22, 2013 11:48 AM by Wang Liyu

    [WELD 1.x, CDI 1.0] CDI Programmatic lookup - is calling creationalContext.release() necessary?

    Egor Kolesnikov Newbie

      Hi everyone,

       

      Before I get to the question - yes, I know, that programmatic lookup is bad, and I should really be using @Inject annotation. However, we all live in the real world where legacy code has its own constraints.

      Right now I am dealing with good 'ole ServiceLocator implementation that orchestrates many DI frameworks that crept into the system over the years - namely, EJB2, EJB3, Guice and Spring. Don't ask. :-)

      My ultimate goal is to eventually "rule them all" with CDI/EJB3 stack and minimise framework diversity.

       

      Right now I'm replacing guice/spring lookups with the CDI and came across this very famous piece of code available everywhere on the internet:

       

       

      private <T> T cdiResolve(Class<T> beanInterface) {BeanManager beanManager = (BeanManager) InitialContext.doLookup("java:comp/BeanManager");
      Bean<T> bean = (Bean<T>) beanManager.resolve(beanManager.getBeans(beanInterface));
      if (bean != null) {
          CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
          if (creationalContext != null) {
              T instance = (T) beanManager.getReference(bean, beanInterface, creationalContext);
              return instance;
          }
      }
      }
      

       

      What's a bit unsettling, though, is that creationalContext is getting created, but not released nor destroyed. Is there a risk of memory leak, shall I call creationalContext.release() at some point, or I'm being paranoid and Weld will take care of my creationalContexts?

       

      Thanks a lot in advance.