2 Replies Latest reply on May 3, 2011 6:51 AM by Bryn Cooke

    PreDestroy not being invoked in Weld SE shutdown

    Aaron Anderson Newbie
      I am using Weld 1.1.0 final and have created a @Singleton bean that starts a web server listener in a @PostConstruct method and shuts it down in a @PreDestroy method. in my CDI extension I "start" the bean by executing the following code in my extension's @Observes AfterDeploymentValidation event.

      Set<Bean<?>> beans = bm.getBeans(WebServer.class, new AnnotationLiteral<Any>() {
                      });
                      if (beans.size() > 0) {
                              Bean<?> bean = beans.iterator().next();
                              bm.getReference(bean, WebServer.class, bm.createCreationalContext(bean));
                      }

                    

      The @PostCreate method is invoked and everything is fine until I shutdown the container using the Weld classes shutdown() method. According to my logs the @PreDestroy method is not invoked. I thought the problem might be with the createCreationalContext() invocation so I cached it and in a @Observes BeforeShutdown method invoked the release method on it to no effect.

      Any ideas why Weld would not invoke the @PreDestroy method on container shutdown? I would think on shutdown the container would automatically releease all contexts and destroy all managed beans.
        • 1. Re: PreDestroy not being invoked in Weld SE shutdown
          Aaron Anderson Newbie

          Perhaps because the reference is accessed outside the container through the BeanManager it must be manually destroyed in the same fashion it was created. This code works as expected.



          CreationalContext<WebServer> webServerCtx;
          Bean<WebServer> webserverBean;
          WebServer webServer;
          
          public void afterDeploymentValidation(@Observes AfterDeploymentValidation adv, BeanManager bm) {
          
                    Set<Bean<?>> beans = bm.getBeans(WebServer.class, new AnnotationLiteral<Any>() {
                    });
                    if (beans.size() > 0) {
                         webserverBean = (Bean<WebServer>)beans.iterator().next();
                         webServerCtx = bm.createCreationalContext(webserverBean);
                         webServer = (WebServer)bm.getReference(webserverBean, WebServer.class, webServerCtx);
                    } else {
                         System.out.println("Can't find class " + WebServer.class);
                    }
          }
          
          
          public void beforeShutdown(@Observes BeforeShutdown adv, BeanManager bm) {
                 if (webServer!=null){
                      webserverBean.destroy(webServer, webServerCtx);
                 }
          }
          


          • 2. Re: PreDestroy not being invoked in Weld SE shutdown
            Bryn Cooke Newbie

            Changing from Singleton to ApplicationScoped worked for me.