Hi Marco!

Please don't do beans.iterator().next() - you can do BeanManager#resolve() 
instead. 

Also Bean<T> != Contextual Instance of T

You would to create a CreationalContext<T> and invoke BeanManager#getReference

You might take a look at Apache DeltaSpike BeanProvider [1] which provides easy 
helpers for exactly that: getContextualReference(..) 
Plus this also works in environments without a writeable JNDI contract like in 
plain tomcat.

LieGrue,
strub



[1] http://incubator.apache.org/deltaspike/documentation.html



----- Original Message -----
> From: Marco de Booij <[email protected]>
> To: Users OpenEJB <[email protected]>
> Cc: 
> Sent: Saturday, March 30, 2013 6:46 PM
> Subject: CDI instead of JSF
> 
> 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