Can I (and how) lookup CDI managed beans using jav

2020-02-08 01:57发布

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.

2条回答
成全新的幸福
2楼-- · 2020-02-08 02:29

You can lookup the BeanManager via JNDI (java:comp/BeanManager) then use the JSR-299 API hung off of the BeanManager to get a contextual reference to a managed bean.

JSR-299 managed beans are not available for direct JNDI lookup.

查看更多
▲ chillily
3楼-- · 2020-02-08 02:47

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();
查看更多
登录 后发表回答