Grails Dependency Injection from Service

200 Views Asked by At

I am trying to injecting my own service elasticsearchService from the following domain class:

class DocumentESO extends ElasticsearchObject{

  ElasticsearchService elasticsearchService

  def afterInsert() {
    elasticsearchService.save(this) // <-- Cannot invoke method save() on null object
  }
}

However, it tells me that it Cannot invoke method save() on null object. Here is my service:

@Transactional
class ElasticsearchService {
    @Transactional
    def save(ElasticsearchObject esObject) {...}
}

Did I misspell something? If I would use ElasticsearchService elasticsearchService = new ElasticsearchService() then it would work, but I don't have the transactional support anymore.

In this answer, robert mentions it needs to initialized, while using meta programming save() for example. Does it mean that I cannot go with dependency injection in this case?

Thus it would be:

  def afterInsert() {
    ElasticsearchService elasticsearchService = new ElasticsearchService()
    elasticsearchService.save(this) 
  }

??

1

There are 1 best solutions below

5
Michal_Szulc On BEST ANSWER

Service injection in GORM entities is disabled by default since Grails 3.2.8.

You can turn on autowiring in this one particular domain class by adding to DocumentESO:

static mapping = {
       autowire true
   }

however it's not recommended: https://grails.org/blog/2017-05-09.html