Search code examples
initializationsharedspock

Initialize object in @Shared or setupSpec()


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?


Solution

  • 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()
       }