adam bien's blog

Startup Hook / Initialization Logic with CDI 📎

The Initialized qualifier is fired when a context is initialized, i.e. ready for use., and can be used to listen for the ApplicationScoped to be "ready".

Now you can use Initialized together with Observes to implement startup logic:


import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Observes;

@ApplicationScoped
public class InitializerOnStart {

    public void onStart(@Observes @Initialized(ApplicationScoped.class) Object pointless) {
        System.out.println("InitializerOnStart.onStart() ");
    }
}

...the same functionality with EJBs:


import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;

@Startup
@Singleton
public class InitializerOnStart {

    @PostConstruct
    public void onStart() { }
}
(EJB example used in: A Java EE 7+ Alternative To EJB Timers)