Adding changes listeners in Grails' GORM

2019-06-08 15:47发布

问题:

I'm new to Grails and I'm using Grails 2.0.1. I want to add a persistence event listener for changes in objects for a domain class, so I tried the code in Bootstrap.groovy as given in the user guide:

def init = {
    applicationContext.addApplicationListener(new FooBarListener())
}

And I get the following error message:

ERROR context.GrailsContextLoader - Error executing bootstraps: No such property: applicationContext for class: BootStrap

How can I get the applicacionContext property from inside the BootStrap class? or Is the documentation outdated and there is a new/better way to add domain changes listeners?.

Thanks in advance.

回答1:

import org.codehaus.groovy.grails.commons.ApplicationAttributes

class BootStrap {

    def init = {servletContext ->

        def applicationContext = servletContext.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT) 
    }
}


回答2:

The shortest way I know is

class BootStrap {

   def grailsApplication

   def init = { servletContext ->
      def applicationContext = grailsApplication.mainContext
   }
}


回答3:

applicacionContext must be defined in BootStrap. Following should work

     class BootStrap {
       def applicacionContext 

    def init = {
     applicationContext.addApplicationListener(new FooBarListener())
    }

   }