@Singleton and @Startup annotations in Java EE

You can use @Singleton and @Startup in scenarios such as you want some code to execute when the application starts up to set an initial collection of properties. You decide this should be housed within an EJB and there should be only a single instance of this EJB created per JVM.

Unless otherwise specified, the singleton session bean instance is typically initialized when the bean is first used through one of its client views, which is the same as any other session bean. Use the @Startup annotation or the corresponding XML deployment descriptor to mark a bean as a startup bean. Marking a singleton bean as a startup bean means that the EJB container must run the PostConstruct method before it supports any external client requests made to the application to run. A PostConstruct method in a singleton bean can create an EJB timer, add a message to a JMS queue or topic, call an asynchronous EJB method, or initiate other asynchronous mechanisms that call an EJB. However, to avoid a deadlock, the PostConstruct method must not wait for an EJB timer to run, a message-driven bean method to be called, or an asynchronous EJB method to finish.
Application developers can place business logic in the PostConstruct methods of these startup singleton instances to complete tasks that must be performed before any client work being started by the container, such as preloading caches or initiating asynchronous work within the application.

The following example illustrates a singleton session bean with startup initialization:

public class ConfigurationBean implements Configuration {


public void initialize() {

// 1. Create the database table if it does not exist.

// 2. Initialize settings from the database table.

// 3. Load a cache.

// 4. Initiate asynchronous work (for example, work to a messaging

// queue or to calls to asynchronous session bean methods.


// ...


Instead of using an annotation, you can specify the same metadata using the XML deployment descriptor. Specify true to mark this singleton bean as a startup singleton. Conversely, specify false, and the @Startup annotation is overridden, if it exists on the class file.



Popular posts from this blog