Search code examples
springspring-mvcgrailsgrails-3.1

Can I call a grails service in a domain object constructor?


Grails version: 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). I would like the VersionedDomainClass to handle calling the service, but when I try to do this:

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:

Caused by: java.lang.NullPointerException: Cannot invoke method getNextVersion() on null object

I don't need any VersionedDomainClass instantiated at startup; it looks like Spring is trying to create it's own isntance of the domain class, perhaps? is there any way to prevent Spring from doing this until the Service beans have been created?


Solution

  • Instead of using the constructor, you can use beforeInsert() to initialize 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)
        }
    }