Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method on class [] was used outside of a Grails application

Previous questions on this error refer to a hibernate version issue or running a test. I do not think this is the case here.

In a Grails Service class I have:

private static User anon = User.findByUsername('anonymous')

and this is creating the error:

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.

I am trying to instantiate a private static attribute with an object stored in the database, but I must be doing something terribly wrong. Thanks for any help, suggestions and pointers.

like image 715
malc Avatar asked Aug 28 '14 15:08

malc


2 Answers

It won't work to make this static, because that will try and make the findByUsername call at the point when the service class is loaded, which is before the GrailsApplication initialization procedure is complete. The earliest you can reliably call GORM methods is at BootStrap time, so what I tend to do in these sorts of situations is create an initialization method on the service and then call that method from the BootStrap init closure.

like image 139
Ian Roberts Avatar answered Sep 20 '22 22:09

Ian Roberts


I know this is old, but, which version of grails were you using? I had the same problem after a migration from grails 2.3 to grails 2.5.

After some pretty painful investigation, I found out that problem is when running tests with new fork mode properties, and is easy to solve by removing these options from 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]
]

Regards.

like image 39
GSAN Avatar answered Sep 21 '22 22:09

GSAN