Grails版本:3.1.2

每当创建域对象(VersionedDomainClass)的新实例时,我都会调用一个版本控制服务(VersionService)。我希望VersionedDomainClass处理调用服务,但是当我尝试这样做时:

class VersionedDomainClass {

    transient def versionService

    short businessVersion

    VersionedDomainClass () {
         this.businessVersion = versionService.getNextVersion(this.class)
    }

}

构造函数在启动期间被调用,此时versionService仍然为null,因此我得到了NPE:
Caused by: java.lang.NullPointerException: Cannot invoke method getNextVersion() on null object

我不需要在启动时实例化任何VersionedDomainClass;看起来像Spring试图创建它自己的域类的标志,也许吗?有什么方法可以阻止Spring在创建Service Bean之前执行此操作?

最佳答案

除了使用构造函数,您还可以使用beforeInsert()初始化businessVersion:

class VersionedDomainClass {

    transient def versionService

    short businessVersion

    /*
     * I get called only once;
     * right before I'm saved in the db for the first time.
     */
    def beforeInsert() {
        businessVersion = versionService.getNextVersion(this.class)
    }
}

07-24 08:36