3 Replies Latest reply on May 4, 2010 8:27 PM by nickarls

    Get bean reference on a non EJB aware context

    cjalmeida

      Hi,


      I needed to access a managed bean on a non-managed PhaseListener and had to write (straight from Seam3Faces module)


      BeanManager beanManager;
      try {
           beanManager = (BeanManager) new InitialContext().lookup("java:app/BeanManager");
      } catch (NamingException e) {
           throw new RuntimeException(e);
      }
      Bean<ILoginService> bean = (Bean<ILoginService>) beanManager.getBeans(ILoginService.class).iterator().next();
      CreationalContext<ILoginService> context = beanManager.createCreationalContext(bean);
      ILoginService loginService = (ILoginService) beanManager.getReference(bean, LoginService.class, context);



      IMO, such thing should be part of Weld API (even if as an extension). Something like a static helper method on BeanManager.


      ILoginService service = BeanManager.inject(<type>,<qualifiers>...);

        • 1. Re: Get bean reference on a non EJB aware context
          nickarls

          There is a Java services based BeanManagerAware superclass in weld-extensions under construction that has a getBeanManager(). I also recall seeing the famous three-liner for getting the reference somewhere in extensions but I can't seem to find it now. It will be there sooner or later, anyway so you'll be able to do something like


          getBeanManager().getReference(Foo.class);
          




          etc

          • 2. Re: Get bean reference on a non EJB aware context
            cjalmeida

            The static helper is probably a better idea since you need to extend nothing. Having to extend BeanManagerAware might pose some restriction on integrating frameworks that also uses extensions.

            • 3. Re: Get bean reference on a non EJB aware context
              nickarls

              That was one design option but I think Pete wanted it to be as ugly as possible so it wouldn't be used that much ;-) There was also something with static and classloaders, can't remember now. It might of course be subject to change since it's just a minor implementation detail.