【问题标题】:How to get the session or web application context when running via run-script?通过运行脚本运行时如何获取会话或 Web 应用程序上下文?
【发布时间】:2012-02-21 11:11:07
【问题描述】:

我有一个使用 Grails 的 run-script 运行的 groovy 脚本。它从大量静态数据中填充数据库。因为this Grails/Hibernate session issue,我不得不偶尔清除会话。如果我不这样做,则该应用程序内存不足。因此,当使用run-script 运行时,我如何获得对会话或 Web 应用程序上下文 (GrailsWebApplicationContext) 的引用?

【问题讨论】:

    标签: grails


    【解决方案1】:

    如果您查看 _RunScript.groovy 内部,您会看到应用程序上下文和 GrailsApplication 对象被注入到脚本的绑定中。

    def shell = new GroovyShell(classLoader, new Binding(ctx: appCtx, grailsApplication: grailsApp))
    

    一旦你有了这些,访问当前会话就很容易了,在你的脚本中只需询问当前会话的会话工厂,你就可以清除它:

    def currentSession = ctx.sessionFactory.currentSession
    currentSession.clear()
    

    【讨论】:

    • 很好地解释了ctx 是如何被注入的。
    • 这里的答案是使用 run-scripts 命令在 Grails 应用程序上下文中运行的 Groovy 脚本。一些网站提到使用includeTargets << grailsScript("..."),但这对于运行脚本来说不是必需的,如答案中所述。如果您在脚本中定义@Field 时尝试访问ctx,可能会让您失望。在评估@Field 声明时,ctx 绑定尚未发生。推迟 @Fields 中引用 ctx 的分配,只需在另一行定义它们,它就会起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    相关资源
    最近更新 更多