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.


Recommended Articles

Dynamically Register Servlets and Filters in Java EE 6 Applications

Learn how to use the ServletContext class to programmatically add servlets and filters to a web application during startup with Java EE 6.

Fix Java.lang.OutOfMemoryError: Compressed Class Space Error on 64-bit Platforms

Learn how to resolve 'java.lang.OutOfMemoryError: Compressed class space error' in Java 1.8 and later versions.

Enhance Java Applications with Hidden Classes and Runtime Interceptors

Discover how to leverage hidden classes in Java 15+ for dynamic class loading and runtime interceptors. Learn the steps from coding your custom Hidden Class to invoking it within another application.

Create Minimal Java LDAP Client Using Docker in Just a Few Steps

Learn how to create a minimal Java LDAP client with Docker and openLDAP, including setting up an LDAP server and testing connectivity. #Java #LDAP #Docker #OpenLDAP #JBang