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:

package com.mastertheboss;

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

@Startup
@Singleton
public class StartupBean {
  private String status;
 
  @PostConstruct
  public 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:

package com.mastertheboss;

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

@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:

package com.mastertheboss;

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

@Startup
@Singleton
@DependsOn("StartupBean")
public class PostStartupBean {
 
  @PostConstruct
  public void init() {
    // Here init your resources
  }
  
}

Found the article helpful? if so please follow us on Socials