Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nineninesevenfour/d9c643ff5a7f98302f89687720d0a138 to your computer and use it in GitHub Desktop.
Save nineninesevenfour/d9c643ff5a7f98302f89687720d0a138 to your computer and use it in GitHub Desktop.
A bridge between the ServletContext life cycle events and CDI observers (with example observer ApplicationInitializer)
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Observes;
import javax.servlet.ServletContext;
// uncomment line if you want the instance to be retained in application scope
// @ApplicationScoped
public class ApplicationInitializer
{
public void onStartup(@Observes @Initialized(ApplicationScoped.class) ServletContext ctx)
{
System.out.println("Initialized web application at context path " + ctx.getContextPath());
}
}
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Destroyed;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Any;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.lang.annotation.Annotation;
@WebListener
public class ServletContextLifecycleNotifier implements ServletContextListener
{
@Inject @Any
private Event<ServletContext> servletContextEvent;
@Override
public void contextInitialized(ServletContextEvent sce)
{
servletContextEvent.select(new Initialized() {
@Override
public Class<? extends Annotation> annotationType() {
return Initialized.class;
}
@Override
public Class<? extends Annotation> value() {
return ApplicationScoped.class;
}
}).fire(sce.getServletContext());
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
servletContextEvent.select(new Destroyed(){
@Override
public Class<? extends Annotation> annotationType() {
return Destroyed.class;
}
@Override
public Class<? extends Annotation> value() {
return ApplicationScoped.class;
}
}).fire(sce.getServletContext());
}
}
@nineninesevenfour
Copy link
Author

A variant of https://gist.github.com/mojavelinux/637959 with the qualifiers replaced by the ones from package javax.enterprise.context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment