Grails初始化类

时间:2014-06-27 16:24:42

标签: class grails groovy initialization

我有一个关于初始化与groovy / grails的问题。当我有以下类时,sInstance不会进入SService初始化。

class A {

    String sInstance
    String app
    String dbInstance

    SService s = new SService(sInstance:sInstance, app:app)
}

SService类:

class SService {

    String sInstance
    String app

public getSInstance{
    return sInstance
    }
}

返回null,其中

class A {

    String sInstance
    String app
    String dbInstance

public initializeSService{
    SService s = new SService(sInstance:sInstance, app:app)
    }
}

从SService类返回sInstance变量。

为什么这样,我如何使用A类构造函数初始化SService对象?

1 个答案:

答案 0 :(得分:2)

你不能这样做:

class A {

    String sInstance
    String app
    String dbInstance

    SService s = new SService(sInstance:sInstance, app:app)
}

问题在于,当您创建SService的实例时,尚未初始化sInstance。如果要将sInstance传递给A类中某个其他类的构造函数,则必须在为sInstance赋值之后执行此操作,就像在完全构造A之后调用的方法一样。

编辑:

试图澄清以下评论中的内容:

class A {
    String sInstance
    String app
    String dbInstance

    void anyMethod() {
        // this will work as long as you have initialized sInstance
        SService s = new SService(sInstance:sInstance, app:app)
    }
}

根据你真正想做的事情,可能会朝这个方向发展:

class A {
    String sInstance
    String app
    String dbInstance
    SService s

    void initializeS() {
        if(s == null) {
            // this will work as long as you have initialized sInstance
            s = new SService(sInstance:sInstance, app:app)
        }
    }
}

或者:

class A {
    String sInstance
    String app
    String dbInstance
    SService theService

    SService getTheService() {
        if(theService == null) {
            // this will work as long as you have initialized sInstance
            theService = new SService(sInstance:sInstance, app:app)
        }
        theService
    }

    def someMethodWhichUsesTheService() {
        getTheService().doSomethingToIt()
    }
}