9Jul/120

CDI BeforeShutdown Event not fired

Ever wondered why the JEE6 CDI Event BeforeShutdown isn't fired when the container shuts down as described in its javadoc?

Well, this is because it's one of the container lifecycle events that are not accessible for normal CDI managed beans. To get access to these special events, your implementation has to be an CDI Extension.

First, implement the Extension interface:

package org.nightprogrammer.examples.cdi;
 
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.BeforeShutdown;
import javax.enterprise.inject.spi.Extension;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class BeforeShutdownTest implements Extension {
 
	private static final Logger log = LoggerFactory.getLogger(BeforeShutdownTest.class);
 
	public void onShutdown(@Observes BeforeShutdown beforeShutdownEvent) {
		log.debug("shutdown event received!");
	}
}

Second, create a META-INF/services/javax.enterprise.inject.spi.Extension file containing the full qualified classname of your Extension:

org.nightprogrammer.examples.cdi.BeforeShutdownTest

That's it! Now you receive the Event as soon as the container goes down. Would be great if the javadoc would mention that directly in the BeforeShutdown Event though. That would have saved me an hour of research :(.

What do you use for cleaning up resources before a container shuts down?

(Besides contextDestroyed() for webapps and addShutdownHook() for JavaSE applications.)

Posted by Veit Guna

Tagged as: CDI, Events

Recent search terms: