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!
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.
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
I would try injecting the service into the Bootstrap and then calling the method from the destroy block, since the destroy block is executed when the application is terminated, something like this:
class BootStrap {
def myService
def init = {servletContext ->
}
def destroy = {
myService.cleanUp()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With