[英]Can I call a grails service in a domain object constructor?
Grails version: 3.1.2 Grails 版本:3.1.2
I have a versioning service (VersionService) that I would like to call whenever I create a new instance of a domain object (VersionedDomainClass).我有一个版本控制服务 (VersionService),每当我创建域对象 (VersionedDomainClass) 的新实例时,我都想调用它。 I would like the VersionedDomainClass to handle calling the service, but when I try to do this:
我希望 VersionedDomainClass 来处理调用服务,但是当我尝试这样做时:
class VersionedDomainClass {
transient def versionService
short businessVersion
VersionedDomainClass () {
this.businessVersion = versionService.getNextVersion(this.class)
}
}
the constructor gets called during startup, at which point versionService is still null so I get a NPE:构造函数在启动期间被调用,此时 versionService 仍然为空,所以我得到了一个 NPE:
Caused by: java.lang.NullPointerException: Cannot invoke method getNextVersion() on null object
I don't need any VersionedDomainClass instantiated at startup;我不需要在启动时实例化任何 VersionedDomainClass; it looks like Spring is trying to create it's own isntance of the domain class, perhaps?
看起来 Spring 正在尝试创建它自己的域类,也许? is there any way to prevent Spring from doing this until the Service beans have been created?
在创建服务 bean 之前,有什么方法可以阻止 Spring 这样做吗?
Instead of using the constructor, you can use beforeInsert()
to initialize businessVersion
:您可以使用
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.