简体   繁体   English

我可以在域对象构造函数中调用 grails 服务吗?

[英]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.

相关问题 服务没有注入Grails域类,Grails 2.0.0和2.0.3 - Service is not getting injected into Grails domain class , Grails 2.0.0 and 2.0.3 如何在控制器单元测试中模拟 grails 4 服务 - How can I mock a grails 4 service in a controller unit test 如何在Grails服务中访问会话Cookie? - How can I access the Session Cookie in a Grails Service? Grails 2 - 无法创建spring安全域对象 - Grails 2 - Cannot create spring security domain object 为什么我不能将字符串传递给 Spring 中的 @Service class 构造函数? - Why can't I pass a String to a @Service class constructor in Spring? 在Grails应用程序中注入到Java服务中时,Grails服务中缺少动态域方法 - Dynamic domain methods missing from grails service when injected into java service in grails app 如何从thymeleaf文本框调用带有两个参数的构造函数? - How can I call a constructor with two parameters from thymeleaf textbox? Grails 3.1.16-计划服务的会话范围服务的调用方法 - Grails 3.1.16 - Call method of session scope service from scheduled service 调用 Spring 服务并通过构造函数发送参数 - Call Spring service and send params via Constructor 在域对象约束中指定grails浮点精度,怎么办? - Specifying grails floating point precision in domain object constraint, how?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM