SeamFramework.orgCommunity Documentation

Chapter 25. Retrieving the BeanManager from the servlet context

Typically, the BeanManager is obtained using some form of injection. However, there are scenarios where the code being executed is outside of a managed bean environment and you need a way in. In these cases, it's necessary to lookup the BeanManager from a well-known location.

Warning

In general, you should isolate external BeanManager lookups to integration code.

The standard mechanism for locating the BeanManager from outside a managed bean environment, as defined by the JSR-299 specification, is to look it up in JNDI. However, JNDI isn't the most convenient technology to depend on when you consider all popular deployment environments (think Tomcat and Jetty).

As a simpler alternative, Solder binds the BeanManager to the following servlet context attribute (whose name is equivalent to the fully-qualified class name of the BeanManager interface:

javax.enterprise.inject.spi.BeanManager

Solder also includes a provider that retrieves the BeanManager from this location. Anytime the Solder module needs a reference to the BeanManager, it uses this lookup mechanism to ensure that the module works consistently across deployment environments, especially in Servlet containers.

You can retrieve the BeanManager in the same way. If you want to hide the lookup, you can extend the BeanManagerAware class and retrieve the BeanManager from the the method getBeanManager(), as shown here:



public class NonManagedClass extends BeanManagerAware {
    public void fireEvent() {
        getBeanManager().fireEvent("Send me to a managed bean");
    }
}
    

Alternatively, you can retrieve the BeanManager from the method getBeanManager() on the BeanManagerLocator class, as shown here:



public class NonManagedClass {
    public void fireEvent() {
        new BeanManagerLocator().getBeanManager().fireEvent("Send me to a managed bean");
    }
}
    

Tip

The best way to transfer execution of the current context to the managed bean environment is to send an event to an observer bean, as this example above suggests.

Under the covers, these classes look for the BeanManager in the servlet context attribute covered in this section, amongst other available strategies. Refer to the BeanManager provider chapter of the Seam Solder reference guide for information on how to leverage the servlet context attribute provider to access the BeanManager from outside the CDI environment.