Search code examples
javacdiweld

Why has an @ApplicationScoped bean a new instance in the BeforeShutdown phase of my CDI extension ?


I would like to make some clean up on a bean when I shutdown a CDI application. For example, I would like to close an IO connection. Of course, here, the bean is marked as @ApplicationScoped.

To manage this I wrote an extension and observe the BeforeShutdown event, and then I select my bean to call a clean up method :

public void beforeShutdown(@Observes BeforeShutdown beforeShutdown) {
    SomeBean obj = CDI.current().select(SomeBean.class).get();
    obj.cleanup();
}

My problem is that I have access to a new instance in this method. Not the instance I got in the whole application.

If you want to see this instance problem, I've made a repo on github to show it : https://github.com/hasalex/cdi-extension-demo.

So I have 2 questions :

  • Why do I get a new instance ?
  • Is there an other way to cleanup my bean at the end of the application ? (in SE and in WildFly environments)

Solution

  • look here: http://docs.jboss.org/cdi/spec/1.1.EDR1/html/spi.html#provider

    11.5.4. BeforeShutdown event

    The container must fire a final event after it has finished processing requests and destroyed all contexts.

    Maybe you want to use @PreDestroy: http://docs.oracle.com/javaee/6/tutorial/doc/gmgkd.html

    Annotate the declaration of the method with the javax.annotation.PreDestroy annotation.

    CDI calls this method before starting to destroy the bean.