【问题标题】:Why is Grails plugin's BootStrap not executing?为什么 Grails 插件的 BootStrap 没有执行?
【发布时间】:2014-07-04 03:48:34
【问题描述】:

我创建了一个 Grails 插件 (grails create-plugin myplugin1),并注意到没有像您通常在创建 Grails 应用程序时那样创建的 myapp1/grails-app/conf/BootStrap.groovy

我这样创建了一个:

class BootStrap {
    def init = {
        println("Hello! The plugin is bootstrapping...")
    }

    def destroy = {
    }
}

然后我将插件包含在 Grails 应用程序中(通过在应用程序的 BuildConfig.groovy 中添加 myplugin1 作为插件)。当我发出grails run-app 时,我看不到上面的println 执行过。

Grails 插件不使用BootStrap.groovy 吗?如果是这样,我应该将加载插件时需要执行的“引导”代码放在哪里?否则,如果我在上面这样做是正确的,为什么我没有看到“Hello!The plugin is bootstrapping...”消息打印出来?

【问题讨论】:

  • solution 为我工作,但它是 Grails 3 的问题。您使用的是哪个 Grails 版本?

标签: grails grails-plugin bootstrapping


【解决方案1】:

和往常一样,从编写和维护得很好的documentation开始。

插件不包含 Bootstrap.groovy。以下内容不包括在插件中(取自文档)。

  • grails-app/conf/BootStrap.groovy
  • grails-app/conf/BuildConfig.groovy(虽然它是用来生成dependencies.groovy)
  • grails-app/conf/Config.groovy
  • grails-app/conf/DataSource.groovy(和任何其他 *DataSource.groovy)
  • grails-app/conf/UrlMappings.groovy
  • grails-app/conf/spring/resources.groovy
  • /web-app/WEB-INF 中的所有内容
  • /web-app/plugins/** 中的所有内容
  • /test/** 中的所有内容
  • /.svn//CVS/ 中的 SCM 管理文件

为了在插件启动时运行代码,您需要使用 doWithSpringdoWithApplicationContext 挂钩到插件的运行时配置(取决于您需要做什么)。

所有这些以及更多内容都在documentation 中进行了解释。一个例子可能是:

// MyFancyPlugin.groovy
  ...
  def doWithApplicationContext = { appCtx ->
      def sessionFactory = appCtx.sessionFactory
      // do something here with session factory
  }
  ...

【讨论】:

    【解决方案2】:

    插件的 BootStrap 已从插件包中排除。您必须在插件描述符中执行初始化阶段,在以下一个或几个闭包中:

    def doWithSpring = {
      def appName = application.metadata.'app.name'
    }
    
    def doWithDynamicMethods = { ctx ->
        // TODO Implement registering dynamic methods to classes (optional)
    }
    
    def doWithApplicationContext = { applicationContext ->
        // TODO Implement post initialization spring config (optional)
    }
    

    【讨论】:

    • 介意我们将所有答案合并到@injecteer 的答案中并删除我们的答案吗?这样我们就可以为未来的用户提供一个可靠的答案?
    【解决方案3】:

    需要在启动时运行的代码应该放在插件描述符 (MyPlugin1GrailsPlugin.groovy) 的 doWithApplicationContext 闭包中。

    或者,将其称为其他名称(例如 MyPluginBootStrap.groovy),因为它只是在打包插件时排除的特定类 BootStrapUrlMappings,但 任何 类的名称结束 BootStrap 被认为是引导人工制品。

    【讨论】:

    • 介意我们将所有答案合并到@injecteer 的答案中并删除我们的答案吗?这样我们就可以为未来的用户提供一个可靠的答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多