Initialization of Singleton Session Bean

7 March 2012 By Nithya Vasudevan 1,914 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • The EJB container is responsible for determining when to initialize a singleton session bean instance.
  • However, the Singleton Session bean can be requested to be initialized by the container upon application startup. This is called eager initialization and can be done by using the @Startup annotation in the implementation class.
  • The singleton session bean is initialized before the EJB container delivers client requests to any enterprise beans in the application.
  • This allows the singleton session bean to perform, for example, application startup tasks.

The following singleton session bean stores the status of an application and is eagerly initialized:

public class StatusBean {
  private String status;

  void init {
    status = "Ready";

Sometimes multiple singleton session beans are used to initialize data for an application and therefore must be initialized in a specific order. In these cases, use the @DependsOn annotation to declare the startup dependencies of the singleton session bean.

The @DependsOn annotation’s value attribute is one or more strings that specify the name of the target singleton session bean. If more than one dependent singleton bean is specified in @DependsOn, the order in which they are listed is not necessarily the order in which the EJB container will initialize the target singleton session beans.

The following singleton session bean, PrimaryBean, should be started up first:

public class PrimaryBean { … }

SecondaryBean depends on PrimaryBean:

public class SecondaryBean { … }

This guarantees that the EJB container will initialize PrimaryBean before SecondaryBean.

The following singleton session bean, TertiaryBean, depends on PrimaryBean and SecondaryBean:

@DependsOn({"PrimaryBean", "SecondaryBean"})
public class TertiaryBean { ... }

SecondaryBean explicitly requires PrimaryBean to be initialized before it is initialized, through its own @DependsOn annotation. In this case, the EJB container will first initialize PrimaryBean, then SecondaryBean, and finally TertiaryBean.

If, however, SecondaryBean did not explicitly depend on PrimaryBean, the EJB container may initialize either PrimaryBean or SecondaryBean first. That is, the EJB container could initialize the singletons in the following order: SecondaryBean, PrimaryBean, TertiaryBean.

Tags: , ,