Adding changes listeners in Grails' GORM

2019-06-08 16:23发布

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.

3条回答
老娘就宠你
2楼-- · 2019-06-08 16:28

The shortest way I know is

class BootStrap {

   def grailsApplication

   def init = { servletContext ->
      def applicationContext = grailsApplication.mainContext
   }
}
查看更多
女痞
3楼-- · 2019-06-08 16:40

applicacionContext must be defined in BootStrap. Following should work

     class BootStrap {
       def applicacionContext 

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

   }
查看更多
ゆ 、 Hurt°
4楼-- · 2019-06-08 16:45
import org.codehaus.groovy.grails.commons.ApplicationAttributes

class BootStrap {

    def init = {servletContext ->

        def applicationContext = servletContext.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT) 
    }
}
查看更多
登录 后发表回答