Friday, June 29, 2012

Alternative to bean lookup from BeanManager from CDI

Suppose I have a utility object Util which is in application-scoped singleton. In traditional programming model, this object is constructed at application startup using its constructor. At any code location(bean or not bean), I can hold a reference through a static member like this Util.instance.

public class Util
{
  public static Util instance;
@Inject Field f1;
...
 }

In CDI, reference to Util has to be injected. To be injected, your code location should be a CDI bean.   You can not use Util constructor directly since some of its fields such as f1 need injecting from CDI. Its creation needs to be controlled by CDI. You can of course using BeanManager from CDI to look up the singleton instance. 

Here I give another easy solution not using BeanManager.

@ManagedBean(eager = true)
@ApplicationScoped
public class GlobalObjectFactory
{

   
@Inject Util util;
   
    @PostConstruct
    private void transferReference()
    {
        Util.instance=util;
    }
}


In this example, I have an application-scoped object GlobalObjectFactory which is created at the very beginning of application startup by CDI. Since it is created by CDI, you can ask CDI to inject other bean. Once you have a reference to the injected bean, you can pass the reference to a static member of other class. After this, the reference to the injected bean can be accessed through static member anywhere, bean or non-bean.



No comments:

Post a Comment