Skip to content

Instantly share code, notes, and snippets.

@mojavelinux
Created October 21, 2010 04:53
Show Gist options
  • Save mojavelinux/637959 to your computer and use it in GitHub Desktop.
Save mojavelinux/637959 to your computer and use it in GitHub Desktop.
A bridge between the ServletContext life cycle events and CDI observers (with example observer ApplicationInitializer)
// uncomment line if you want the instance to be retained in application scope
// @ApplicationScoped
public class ApplicationInitializer
{
public void onStartup(@Observes @Initialized ServletContext ctx)
{
System.out.println("Initialized web application at context path " + ctx.getContextPath());
}
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface Destroyed {}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface Initialized {}
@WebListener
public class ServletContextLifecycleNotifier implements ServletContextListener
{
@Inject @Any
private Event<ServletContext> servletContextEvent;
@Override
public void contextInitialized(ServletContextEvent sce)
{
servletContextEvent.select(new AnnotationLiteral<Initialized>() {}).fire(sce.getServletContext());
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
servletContextEvent.select(new AnnotationLiteral<Destroyed>() {}).fire(sce.getServletContext());
}
}
@devpie
Copy link

devpie commented Jan 16, 2013

Great... i searched the whole web for a possibility to get the ServletContext inside my CDI app inside a bean... Thank you very much!!!

@wesleyhales
Copy link

Very nice DanTT, thanks for this!

@jyeary
Copy link

jyeary commented Aug 1, 2013

This was a really helpful solution to an issue I was trying to solve without using additional frameworks like Solder. Thanks Dan.

@lkrzyzanek
Copy link

Very nice example. Thanks.

@icordoba
Copy link

Hello,
the example does not work in WAS Liberty profile if I uncommon ApplicationScoped. I get:
org.apache.webbeans.event.ObserverMethodImpl I Cannot send event to bean in non-active context
probably because ApplicationScope is not yet initialised by the time the ServletContextListener. contextInitialized() method is invoked. Any workarounds? Thanks.

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