Initialize object in @Shared or setupSpec()
Asked Answered
B

1

5

What's the difference between:

@Shared
MyObject myObject = new MyObject()

and

MyObject myObject

def setupSpec() {
    myObject = new MyObjec()
}

Why should I use the @Shared annotation in the second example? Both are only created once, aren't they?

Besmirch answered 5/4, 2016 at 11:28 Comment(0)
S
7

In your second example, you probably got this error:

Error:(22, 9) Groovyc: Only @Shared and static fields may be accessed from here

So you can choose one of those options:

  1. use @Shared annotation and init field in one line

     @Shared
     MyObject myObject = new MyObject()
    
  2. use static and init field in one line

     static MyObject myObject = new MyObject()
    
  3. use @Shared annotation and init field inside setupSpec method

     @Shared
     MyObject myObject
    
     def setupSpec() {
         myObject = new MyObject()
     }
    
  4. use static and init field inside setupSpec method

     static MyObject myObject
    
     def setupSpec() {
         myObject = new MyObject()
     }
    
Stereo answered 9/4, 2016 at 7:39 Comment(2)
But do I have to use @Shared in the second example if I reference a member variable in the setupSpec() ?Besmirch
@Besmirch I edited my answer. I hope now is more cleaner.Stereo

© 2022 - 2024 — McMap. All rights reserved.