Best way for a Grails Service class to detect application shutdown?
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
The grails-app/conf/BootStrap.groovy
can be used when the app starts and stops.
def init = {
println 'Hello World!'
}
def destroy = {
println 'Goodnight World!'
}
Note: When using development mode grails run-app
on some OS's CTL+C
will kill the JVM without the chance for a clean shutdown and the destroy closure may not get called. Also, if your JVM gets the kill -9
the closure wont run either.