How to create a start up class for Enterprise application servers

This article discusses how to create a start up class for a Java Enterprise / Jakarta EE compliant application server such as WildFly.

There is no concept of start up class for an application server however you can deploy an application which contains a component bound to the deployment life cycle.

For example, the javax.servlet.ServletContextListener interface is used for receiving notification events about ServletContext life-cycle changes (initialization or disposal of the Web context). This listener will be triggered when the application is deployed or undeployed. Here is an example of it:

@WebListener
public class MyContextListener implements ServletContextListener {
   @Override
   public void contextInitialized(ServletContextEvent sce) {
      ServletContext context = sce.getServletContext();
      //Add here your start up code
   }
   @Override
   public void contextDestroyed(ServletContextEvent sce) {
   //. . .
   }
}

The other option is to use a Start up Singleton EJB:

@Singleton
@Startup
public class UserRegistry {

        public ArrayList<String> listUsers;
        @PostConstruct
        public void init() {
                listUsers = new ArrayList<String>();
                listUsers.add("administrator");

        }
        public void addUser(String username) {
                listUsers.add(username);
        }
        public void removeUser(String username) {
                listUsers.remove(username);
        }
        public ArrayList<String> getListUsers() {
                return listUsers;
        }
}

As it is plainly evident from the code, besides the @Singleton annotation that we already discussed, the class contains a @Startup annotation too which can be used to activate the EJB as soon as it’s deployed. This will in turn execute the method annotated with @PostConstruct, which might contain some data initialization.

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