【问题标题】:Grails java.lang.IllegalStateException: Method on class [] was used outside of a Grails applicationGrails java.lang.IllegalStateException:类 [] 上的方法在 Grails 应用程序之外使用
【发布时间】:2014-02-21 00:54:26
【问题描述】:

Grails 版本:2.3.4

Hibernate 插件:运行时 ":hibernate:3.6.10.6"

Bootstrap.groovy 中产生错误的那一行:

def adminRole = new Role(authority: 'ROLE_USER').save(flush: true)

实际上任何类(控制器、Bootstrap.groovy)中的任何保存操作都会导致此错误。

但是当我得到在另一台计算机上创建的域类时,它工作正常,没有错误。

有什么建议吗?

谢谢。

完整的堆栈跟踪:

ERROR context.GrailsContextLoader Error initializing the application: Method on class [com.hib.Role] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
java.lang.IllegalStateException: Method on class [com.hib.Role] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
    at BootStrap$_closure1.doCall(BootStrap.groovy:9)
    at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:308)
    at grails.util.Environment.executeForEnvironment(Environment.java:301)
    at grails.util.Environment.executeForCurrentEnvironment(Environment.java:277)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

我没有使用 maven 或 mocking。

Botstrap.groovy

    class BootStrap {

      def init = { servletContext ->

      def adminRole = new Role(authority: 'ROLE_ADMIN').save(flush: true)

   }
            def destroy = {
        }
    }

【问题讨论】:

  • 你能发布你的Bootstrap.groovy吗?听起来您正在 init 闭包之外运行闭包
  • 我添加了 Bootstrap.groovy。相关代码在 init 闭包内。
  • 我认为它与 windows 8 有关。因为在 Mac OS X 和 windows 7 中没有错误。

标签: hibernate grails grails-orm


【解决方案1】:

@user3414639 的提示帮助了我。在我的情况下,代码由几个项目组成,这些项目可以引入一个通用的 GORM 对象模块。当一个 GORM 对象上的 PostInsert 事件触发要保存的不同 GORM 对象(第二个 GORM 对象映射到新数据源)时,我看到了这个错误。

在项目中将新连接添加到项目的 datasource.groovy 的测试部分解决了我的错误。我将继续深入研究配置(不知道为什么 GORM 对象 #1 也没有失败),但至少这让我走上了正确的轨道。

dataSource {
}
environments {
    test {
        dataSource_missing {
            driverClassName = "com.mysql.jdbc.Driver"
            url = "jdbc:mysql://localhost/testdomain?useUnicode=yes&characterEncoding=UTF-8"
            username = ""
            password = ""
        }
    }
}

【讨论】:

    【解决方案2】:

    我在使用 Grails 2.3.6 和 Hibernate 3.6.10.8 时遇到了非常相似的错误。在运行集成测试时尝试对 GORM 对象执行操作时出现。 最后,当我没有在 datasource.groovy 的“环境”的“测试”部分创建数据源时,我在 GORM 域类的映射块中设置了一个数据源。对其进行了排序,并且成功了。

    【讨论】:

    • 你能解释更多吗?项目从2.2.1升级到2.3.9后才出现这个问题?
    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多