Friday, August 24, 2012

Get bean instance in CDI

In some cases it's required to get the bean instance instead of the reference.
You can simply do it with the following method:

public static <T> T getBeanInstance(final Class<T> type, final Class<? extends Annotation> scope, final BeanManager beanManager)
{
   final Context context = beanManager.getContext(scope);
   final Set<<Bean<?>> beans = beanManager.getBeans(type);
   final Bean<T> bean = (Bean<T>) beanManager.resolve(beans);
   final CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);

   return context.get(bean, creationalContext);
}

2 comments:

  1. PLEASE you can explique me when i would use the BeanInstance instead of the reference?
    A case use of it?

    Another question:
    how i can get a @ApplicationScoped BEan eager like the manaagedBEan of JSF but with OWB ?

    i would that the @ApplicationScoped Bean OWB it is created at web application startup.
    Like with the managedBean of JSF2 @ApplicationScoped(eager=true)

    But without the Ejb Singleton with annotation @Startup .

    I would get the @ApplicationScoped at startup web application only with OWB .

    i have read that it is possiblecreate a extension but not understand how to make it.
    mauro
    mauro

    ReplyDelete
  2. UseCase: If you need to pass a bean to another thread.

    Eager Extension: http://ovaraksin.blogspot.de/2013/02/eager-cdi-beans.html

    ReplyDelete