我正在遵循了解 Groovy 变量及其函数中的示例,并具有以下内容。
EnvironmentMgr
是我在其他地方定义的单例类,它可以工作。
@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()
我希望
println
中的 EcsService:setup()
语句打印一次,但它打印了两次调用。这是为什么?我怎样才能让它发挥作用?谢谢。
编辑: 上面的代码在我的 Mac 上按预期工作,就像直接的 Groovy 代码一样,但在 Jenkins 管道中运行时,无法识别静态性。
问题似乎是由于
envMgr
属性在 Jenkins 环境中不表现为静态属性。为了确保 envMgr
属性是 Jenkins 管道中所有 EcsService
实例的共享/静态属性,您可以使用 static 关键字将其显式声明为静态属性:
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
}
}
}