Just copied and formatted an answer from Marek Gregor - SO link: https://stackoverflow.com/a/46580013
There are several possibilities/levels depending on what you want to do:
@WebListener
public class AppInitContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// Your code here
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
}
This alternative allows programmatically adding another servlets, filters, etc. Then add the fully qualified name of your class to the special text file in your war archive:META-INF/services/javax.servlet.ServletContainerInitializer, in order to register your class to be called by container.
public class AppContainerInitializer implements ServletContainerInitializer {
@Override
void onStartup(Set<Class<?>> c, ServletContext ctx) {
// Your code here
}
}
Implement Wildfly (Undertow servlet engine) specific ServletExtension interface in your application.
This alternative allows you to do 'down to the metal changes' in servlet engine. Then add the fully qualified name of your class to the special text file in your war archive:META-INF/services/io.undertow.servlet.ServletExtension, in order to register your class to be called by Undertow servlet container.
public class AppInitExtension implements ServletExtension {
@Override
public void handleDeployment(final DeploymentInfo deploymentInfo, final ServletContextImpl servletContext) {
// Your code here
}
}
For the sake of completeness, if you are using JPA, you could hook before deployment of JPA Entity manager this way (e.g. for performing database upgrade before deployment). Implement Hibernate specific Integrator interface in your application. Then add the fully qualified name of your class to the special text file in your war archive:META-INF/services/org.hibernate.integrator.spi.Integrator, in order to register your class to be called by Hibernate framework.
public class SchemaUpgradeIntegrator implements org.hibernate.integrator.spi.Integrator {
@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
// Starting DB migration
final DataSource dataSource = (DataSource) sessionFactory.getProperties().get("hibernate.connection.datasource");
// Your code here
}
@Override
public void disintegrate(SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {
}
}