How to create an EJB Startup Service

A startup service can be used to eagerly initialize some resources in your application or in external resources.
Thanks to Java EE 6 addition, you don't need anymore vendor solutions which allow to create startup classes.
Just plug in a Bean which is tagged as @Startup and @Singleton

@Startup
@Singleton
public class StartupBean {
  private String status;

  @PostConstruct
  void init {
    status = "Ready";
    // Here init your resources
  }
  ...
}

 

You can monitor the State of your Service by adding a simple property which can be accessed by your clients:

 

@Singleton 
@Startup 
public class StartupBean {
    public enum States {BEFORESTARTED, STARTED, PAUSED, SHUTTINGDOWN};
    private States state;
    @PostConstruct
    public void initialize() {
        state = States.BEFORESTARTED;
        // Perform intialization
        state = States.STARTED;
        System.out.println("Service Started");
    }
    @PreDestroy
    public void terminate() {
        state = States.SHUTTINGDOWN;
        // Perform termination
        System.out.println("Shut down in progress");
    }
    public States getState() {
        return state;
    }
    public void setState(States state) {
        this.state = state;
    }
}

 

Then your client will simply check the state property and verify what's the current state of the service

@EJB

StartupBean ejb;

 

System.out.println("State is "+ejb.getState());

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 javax.ejb.DependsOn annotation to declare the startup dependencies of the singleton session bean.

Here the PostStartupBean will be fired after the StartupBean is initialized:

@Startup
@Singleton
@DependsOn("StartupBean")
public class PostStartupBean {
 

  @PostConstruct
  void init {
 
    // Here init your resources
  }
  ...
}

Related articles available on mastertheboss.com

EJB 3.0 tutorial : Session Beans

Enterprise JavaBeans (EJB) technology is a J2EE technology for de

JBoss MDB 3.0

Message-driven beans (MDBs) are stateless, server-side, transacti

JBoss EJB 3 BMT

In a Bean Managed Transaction, the code in the session or message

How do you keep your EJB callbacks separated from biz. methods?

JBoss daily recipe

How to set EJB timeout period ?

JBoss recipe of the day

How to add a Selector with MDB 3.0 ?

Message selectors allow an MDB to be more selective about the mes

Follow us on Twitter