Search code examples
grailsgroovyserviceapplication-lifecycle

Best way for a Grails Service class to detect application shutdown?


I have a Grails service class that needs to do some cleanup when my Tomcat application server is shut down.

I don't see anything in the Grails docs about a service.stop() or destroy() method, or a way to implement any sort of application lifecycle listener.

What's the best way to do this?

Thanks!


Solution

  • You have a couple of options

    Make your service implement org.springframework.beans.factory.DisposableBean

    class MyService implements org.springframework.beans.factory.DisposableBean {
    
        void destroy() throws Exception {
    
        }
    }
    

    Or use an annotation

    class MyService {
    
        @PreDestroy
        private void cleanUp() throws Exception {
    
        }
     }
    

    IMO, the annotation option is preferable, because you can give your destructor method a more meaningful name than destroy and your classes public API doesn't expose the Spring dependency