The class method [] was used outside of the Grails application.

Previous questions about this error are related to a hibernation problem or test execution. I do not think so.

In the Grails service class, I have:

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

and this creates an 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 create an instance of a private static attribute with an object stored in a database, but I have to do something terribly wrong. Thanks for any help, suggestions and pointers.

+6
source share
2 answers

This will not work to make it static , because it will try to call findByUsername at the point when the service class that is before the GrailsApplication initialization procedure is GrailsApplication . The earliest you can reliably call GORM methods is BootStrap time, so what I usually do in such situations is to create an initialization method in the service and then call this method from closing BootStrap init.

+7
source

I know this is old, but which version of the grail did you use? I had the same problem after moving from column 2.3 to grail 2.5.

After some pretty painful research, I found that the problem was running tests with the new fork mode properties, and they are easy to solve by removing these parameters 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] ] 

Sincerely.

+2
source

Source: https://habr.com/ru/post/974495/


All Articles