aandeers
aandeers

Reputation: 451

EJB vs CDI lookup

MyService below is a stateless EJB. Will it behave differently if I look it up with CDI instead when it comes to for example transactions?

    InitialContext initialContext = new InitialContext();
    MyService myService1 = (MyService) initialContext.lookup("...MyService...");

VS

    BeanManager beanManager = CDI.current().getBeanManager();
    Bean<?> bean = beanManager.getBeans(MyService.class).iterator().next();
    CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
    MyService myService2 = (MyService) beanManager.getReference(bean, MyService.class, ctx);

Upvotes: 1

Views: 824

Answers (1)

John Ament
John Ament

Reputation: 11733

With the CDI approach, you're getting a dependent instance. With the EJB approach, you're getting an EJB managed reference.

With Dependent instances, you need to take care to destroy the reference when done, otherwise you may face some memory leaks. The spec actually calls out this issue starting with this section

While in most cases, CDI look up is preferred, if the bean behind it is an EJB and you need to do programmatic lookup, you're better off using the EJB approach.

Upvotes: 1

Related Questions