vrijdag 15 april 2011

Seam 3 / Weld alternative for @Startup annotation

In Seam 2, if you wanted a seam component to be initialized when the application was started up, you could use the @Startup annotation.

In Seam 3 (or better: weld), this annotation is not supported. If you want a bean to be started up when the application starts up, you could write a method which observes an event:

  public class BeanToBeInitializedAtStartup {
public void onStartup(@Observes @Initialized WebApplication webApplication){
//do nothing, bean will be initialized when application is started
    }

  }

However, this means you will need such a method for every bean, which is a lot more of overhead than the simple @Startup annotation.

A solution for this is to use a simple helper class, which initializes all beans which implement some interface you define yourself:

First, you will need an interface. This interface does not require any methods.

  public interface Startup { }


Next, all of the beans you want to be initialized should implement this interface

  public class BeanToBeInitializedAtStartup implements Startup { }
That looks a lot better! Now of course you need some helper class, which initializes all beans which implement the Startup annotation:

  public class BeanStartupHelper {


    public void onStartup(@Observes @Initialized WebApplication webApplication, 
                          BeanManager beanManager) {
      
      for(Bean bean : beanManager.getBeans(Startup.class)){
       CreationalContext context = beanManager.createCreationalContext(bean);
       beanManager.getReference(bean, Startup.class, context);
     }
 
    }
  }

The BeanStartupHelper is actually also a bean, and as you can see, this bean contains a method which observes the initialization of the webapplication. A reference to the BeanManager object is injected as a parameter of this method. We use the BeanManager object to create the beans we need, which are all beans which implement the Startup annotation.

Result
There is a clear separation between the beans themselves and the implementation of the startup method. The only thing needed for your beans is the fact that they need to implement a Startup interface. You only need one method which observes the initialization of your application, in which all 'startup' beans will be initialized!