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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…