Hello,

I have an application that works fine when I have JSF in control of my managed beans. Now I try to replace this with CDI. I replaced (nearly) all the @EJB annotations with @Inject. For the managed beans I added @Named and @SessionScoped (or another scope). The application works fine until I want to access the managed beans through: FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(<bean name>)

Seems logic to me since I do not want to use JSF for that anymore. I searched and found that you can access them through the BeanManager. I get the BeanManager like this:
(BeanManager) initialContext.lookup("java:comp/BeanManager")

When I do a getBeans(<bean name>) then I get a bean with beans.iterator().next() and this is the bean I need. I do a bean.getBeanClass().getName() and the name is correct. When I cast the bean to its class then I get a java.lang.ClassCastException: org.apache.webbeans.component.ManagedBean cannot be cast to

What is my mistake?

I use tomee 1.5.1. My application is packaged as WAR. I added an empty beans.xml into the WEB-INF and in the JAR files in the META-INF where I have the Managed Beans. My faces-config.xml only has a phase-listener defined. I do not know if I still need the phase-listener.

  public static BeanManager getBeanManager() {
    BeanManager beanManager = null;
    try {
      final InitialContext initialContext = new InitialContext();
      beanManager =
          (BeanManager) initialContext.lookup("java:comp/BeanManager");
      System.out.println("Gevonden.");
    } catch(NamingException e) {
      LOGGER.error("BeanManager not found.", e);
    }

    return beanManager;
  }

  public static Bean<?> getBean(String beanname) {
    Set<Bean<?>>  beans = getBeanManager().getBeans(beanname);
    if (beans.isEmpty()) {
      LOGGER.debug("Bean " + beannaam + " not found.");
      return null;
    }
    Bean<?> bean  = beans.iterator().next();
// System.out.println("Bean: " + bean.getBeanClass().getName() + " (" + beans.size() + ")");

    return bean;
  }

Reply via email to