类[]上的方法在Grails应用程序外部使用

类[]上的方法在Grails应用程序外部使用,grails,groovy,static-members,Grails,Groovy,Static Members,前面关于此错误的问题涉及hibernate版本问题或运行测试。我认为情况并非如此 在Grails服务类中,我有: private static User anon = User.findByUsername('anonymous') 这就是产生错误的原因: Caused by IllegalStateException: Method on class [User] was used outside of a Grails application. If running in the cont

前面关于此错误的问题涉及hibernate版本问题或运行测试。我认为情况并非如此

在Grails服务类中,我有:

private static User anon = User.findByUsername('anonymous')
这就是产生错误的原因:

Caused by IllegalStateException: Method on class [User] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

我试图用存储在数据库中的对象实例化一个私有静态属性,但我一定是做错了什么。感谢您的帮助、建议和指点。

将此
设置为静态将不起作用,因为这将尝试在加载服务类时,即
GrailApplication
初始化过程完成之前,调用
findByUsername
。最早可靠地调用GORM方法是在
BootStrap
时间,因此在这种情况下,我倾向于在服务上创建一个初始化方法,然后从
BootStrap
init closure调用该方法。

我知道这很旧,但是,您使用的是哪个版本的grails?从Grails2.3迁移到Grails2.5后,我也遇到了同样的问题

经过一些非常痛苦的调查,我发现问题在于使用新的fork模式属性运行测试时,通过从BuildConfig.groovy中删除这些选项很容易解决:

 grails.project.fork = [
        // configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
        //compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],

        // configure settings for the test-app JVM, uses the daemon by default
        test: false,
        // configure settings for the run-app JVM
        run: [maxMemory: 1536, minMemory: 512, debug: false, maxPerm: 1024, forkReserve:false],
        // configure settings for the run-war JVM
        war: [maxMemory: 1536, minMemory: 512, debug: false, maxPerm: 1024, forkReserve:false],
        // configure settings for the Console UI JVM
        console: [maxMemory: 1536, minMemory: 64, debug: false, maxPerm: 1024]
]

问候。

伊恩,谢谢你的回答