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

后端 未结 2 556
庸人自扰
庸人自扰 2020-12-13 14:55

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

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 15:59

    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 bean = (Bean) bm.getBeans(CrudService.class).iterator().next();
    CreationalContext 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 bean = (Bean) bm.getBeans(CrudService.class).iterator().next();
    CreationalContext 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();
    

提交回复
热议问题