Can I (and how) lookup CDI managed beans using javax.naming.Context#lookup in EJB module?

zacheusz picture zacheusz · Nov 17, 2011 · Viewed 17.7k times · Source

Can I (and if so, how?) lookup CDI managed beans using javax.naming.Context#lookup in EJB module?

I'm using GlassFish v3. I suppose that I can use @Named, but what is JNDI name of CDI managed bean? I want to lookup them from unmanaged POJOs so I can't use @Inject.

Answer

Chris Ritchie picture Chris Ritchie · Mar 10, 2015

You can also access the BeanManager by using CDI.current(), which saves you typing a good few lines of code. Example taken from here

Using CDI.current()

BeanManager bm = CDI.current().getBeanManager();

Using JNDI:

BeanManager bm = null;
try {
    InitialContext context = new InitialContext();
    bm = (BeanManager) context.lookup("java:comp/BeanManager");
} catch (Exception e) {
    e.printStackTrace();
}

Now you have the BeanManager you can access your CDI beans by doing either a type-based lookup or a name-based lookup.

Type based:

Bean<CrudService> bean = (Bean<CrudService>) bm.getBeans(CrudService.class).iterator().next();
CreationalContext<CrudService> ctx = bm.createCreationalContext(bean);
CrudService crudService = (CrudService) bm.getReference(bean, CrudService.class, ctx);

Name-based

Bean bean = bm.getBeans("crudService").iterator().next();
CreationalContext ctx = bm.createCreationalContext(bean);
CrudService crudService = bm.getReference(bean, bean.getClass(), ctx);

Full example:

//get reference to BeanManager
BeanManager bm = CDI.current().getBeanManager();
Bean<CrudService> bean = (Bean<CrudService>) bm.getBeans(CrudService.class).iterator().next();
CreationalContext<CrudService> ctx = bm.createCreationalContext(bean);

//get reference to your CDI managed bean
CrudService crudService = (CrudService) bm.getReference(bean, CrudService.class, ctx);

UPDATE - This can now be achieved in one line if you are using CDI 1.1:

CrudService crudService = CDI.current().select(CrudService.class).get();