I'm following an example in Getting To Know Groovy Variables And Their Functions and have the following. EnvironmentMgr
is a singleton class I've defined somewhere else, and it works.
@Singleton
class EnvironmentMgr {
String ecsCluster = "sandbox"
...
}
abstract class EcsService {
def setup() {
if (envMgr == null) {
println "envMgr is null"
envMgr = EnvironmentMgr.instance
}
}
protected static def envMgr = null
}
class Service1 extends EcsService {
def setup() {
super.setup()
// Do something for Service1
}
}
class Service2 extends EcsService {
def setup() {
super.setup()
// Do something for Service2
}
}
def svc1 = new Service1()
svc1.setup()
def svc2 = new Service2()
svc2.setup()
I expect the println
statement in EcsService:setup()
to be printed once, but it's printed both calls. Why is that? How can I make it work? Thanks.
EDIT: The above code works as expected as straight Groovy code on my Mac, but when run in a Jenkins pipeline, the static-ness isn't recognized.
It seems like the issue is due to the envMgr
property is not behaving as a static property in the Jenkins environment. To ensure that the envMgr
property is a shared/static property across all instances of EcsService
in a Jenkins pipeline, you can explicitly declare it as a static property using the static keyword:
abstract class EcsService {
static def envMgr = null // Declare envMgr as a static property
def setup() {
if (envMgr == null) {
println "envMgr is null"
envMgr = EnvironmentMgr.instance
}
}
}