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

我有一个Grails服务类,当我的Tomcat应用程序服务器关闭时需要进行一些清理。 我没有在Grails文档中看到有关service.stop()或destroy()方法的任何内容,或者实现任何类型的应用程序生命周期监听器的方法。 最好的方法是什么? 谢谢!     
已邀请:
你有几个选择 使您的服务实施
org.springframework.beans.factory.DisposableBean
class MyService implements org.springframework.beans.factory.DisposableBean {

    void destroy() throws Exception {

    }
}
或者使用注释
class MyService {

    @PreDestroy
    private void cleanUp() throws Exception {

    }
 }
IMO,注释选项是首选,因为您可以为析构函数方法提供比ѭ3更有意义的名称,并且您的类公共API不会公开Spring依赖项     
应用程序启动和停止时可以使用
grails-app/conf/BootStrap.groovy
def init = {
  println 'Hello World!'
}

def destroy = {
  println 'Goodnight World!'
}
注意:当在某些操作系统上使用开发模式
grails run-app
时,
CTL+C
会在没有干净关闭的情况下终止JVM,并且可能无法调用destroy闭包。此外,如果您的JVM获得
kill -9
,那么关闭也不会运行。     
我会尝试将服务注入Bootstrap,然后从destroy块调用该方法,因为在应用程序终止时执行destroy块,如下所示:
class BootStrap {

    def myService

    def init = {servletContext ->
    }

    def destroy = {
       myService.cleanUp()
    }
}
    
它与服务处理方法并不完全相同,但我最终做的是使用关闭方法注册Spring Bean,该方法在应用程序停止时被调用。 首先,创建一个bean类,如
grails-app/utils/MyShutdownBean.groovy
,如下所示(类名或方法名称没有任何神圣之处,使用你想要的任何东西):
class MyShutdownBean {
    public void cleanup() {
        // Do cleanup stuff
    }
}
然后在
grails-app/conf/spring/resources.groovy
中注册bean,如下所示:
beans = {
    myShutdownHook(MyShutdownBean) { bean ->
        bean.destroyMethod='cleanup'
    }
}
如果你只想在生产中进行清理,你可以这样注册:
beans = {
    if (!grails.util.GrailsUtil.isDevelopmentEnv()) {
        myShutdownHook(MyShutdownBean) { bean ->
            bean.destroyMethod='cleanup'
        }
    }
}
    

要回复问题请先登录注册