Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...