Grails Service类检测应用程序关闭的最佳方法?

Dea*_*ses 6 service grails groovy application-lifecycle

我有一个Grails服务类,当我的Tomcat应用程序服务器关闭时需要进行一些清理.

我没有在Grails文档中看到有关service.stop()或destroy()方法的任何内容,或者实现任何类型的应用程序生命周期监听器的方法.

最好的方法是什么?

谢谢!

Dón*_*nal 7

你有几个选择

使您的服务实施 org.springframework.beans.factory.DisposableBean

class MyService implements org.springframework.beans.factory.DisposableBean {

    void destroy() throws Exception {

    }
}
Run Code Online (Sandbox Code Playgroud)

或者使用注释

class MyService {

    @PreDestroy
    private void cleanUp() throws Exception {

    }
 }
Run Code Online (Sandbox Code Playgroud)

IMO,注释的选择是最好的,因为你可以给你的析构函数方法更有意义的名称不是destroy和你的类的公共API不公开的Spring依赖


Der*_*ife 5

grails-app/conf/BootStrap.groovy当应用程序启动和停止都可以使用.

def init = {
  println 'Hello World!'
}

def destroy = {
  println 'Goodnight World!'
}
Run Code Online (Sandbox Code Playgroud)

注意:grails run-app在某些操作系统上使用开发模式时,CTL+C如果没有干净关闭的机会,就会终止JVM,并且可能无法调用destroy闭包.此外,如果您的JVM获得kill -9关闭也不会运行.