2

In my Java EE aplication I use the following snippet to obtain BeanManager

public static BeanManager getBeanManager() {
    try {
        InitialContext initialContext = new InitialContext();
        return (BeanManager) initialContext.lookup("java:comp/BeanManager");
    } catch (NamingException e) {
        throw new RuntimeException("Failed to retrieve BeanManager!", e);
    }
}

Would it be safe to use BeanManager as singleton, so I would not have to lookup in initial context each time I need BeenManager?

Oleh Novikov
  • 558
  • 5
  • 17

1 Answers1

2

If you want to use the BeanManager into a standard EE(v6-v7) component then it is perfectly legal and recommended to simply do:

@Inject BeanManager beanManager
Franck
  • 1,754
  • 1
  • 13
  • 14
  • Unfortunally I use BeanManager within Java EE components, which do not provide a way of using CDI. One of them is ExceptionMapper. Actually it is the reason why I need a BeanManager in the first place, I need to have a way to access EJBs – Oleh Novikov Aug 14 '15 at 14:03
  • I am using wildfly 8.1.0.Final which comes with weld 2.1 and resteasy 3.0.8 and can use @Inject inside ExceptionMapper. – Franck Aug 14 '15 at 14:19
  • 1
    If you're really stuck I suggest to use delta spike Bean Manager Provider: https://deltaspike.apache.org/documentation/core.html#BeanManagerProvider – Franck Aug 14 '15 at 14:20
  • well I am kinda stuck with Glassfish 3. For me injection to ExceptionMapper does not work there. I am not sure whether I am able to convince my team to use DeltaSpike. But thank you for the hint! – Oleh Novikov Aug 14 '15 at 16:07