Grails文档中的自定义事件侦听器示例

nic*_*dos 3 grails bootstrapping grails-orm mongodb

我正在尝试添加自定义GORM事件侦听器类Bootstrap.groovy,如Grails文档中所述,但它不适用于我.以下是直接来自文档的代码:

def init = {
    application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
        applicationContext.addApplicationListener new MyPersistenceListener(datastore)
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,编译器会抱怨application和applicationContext为null.我已经尝试将它们添加为类级别成员,但它们没有神奇的有线服务风格.我到目前为止最接近的是:

def grailsApplication
def init = { servletContext ->
    def applicationContext = servletContext.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT)
    grailsApplication.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
        applicationContext.addApplicationListener new GormEventListener(datastore)
    }
}
Run Code Online (Sandbox Code Playgroud)

但我仍然得到错误:java.lang.NullPointerException: Cannot get property 'datastores' on null object.

谢谢阅读...

编辑:版本2.2.1

Gra*_*her 8

如果你这样做:

ctx.getBeansOfType(Datastore).values().each { Datastore d ->
   ctx.addApplicationListener new MyPersistenceListener(d)
}
Run Code Online (Sandbox Code Playgroud)

这应该可以在不需要安装Hibernate插件的情况下工作


Bur*_*ith 5

这看起来应该有效,尽管我的做法有点不同.BootStrap.groovy确实支持依赖注入,所以你可以注入grailsApplicationbean,但你也可以eventTriggeringInterceptor直接注入:

class BootStrap {

   def grailsApplication
   def eventTriggeringInterceptor

   def init = { servletContext ->
      def ctx = grailsApplication.mainContext
      eventTriggeringInterceptor.datastores.values().each { datastore ->
         ctx.addApplicationListener new MyPersistenceListener(datastore)
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

在这里我仍然注入grailsApplication但只是因为我需要访问ApplicationContext注册监听器.这是我的倾听者(比文档声称最简单的实现更简单;)

import org.grails.datastore.mapping.core.Datastore
import org.grails.datastore.mapping.engine.event.AbstractPersistenceEvent
import org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener

class MyPersistenceListener extends AbstractPersistenceEventListener {

   MyPersistenceListener(Datastore datastore) {
      super(datastore)
   }

   protected void onPersistenceEvent(AbstractPersistenceEvent event) {
      println "Event $event.eventType $event.entityObject"
   }

   boolean supportsEventType(Class eventType) { true }
}
Run Code Online (Sandbox Code Playgroud)