在Grails 2.5.4中将AbstractPersistenceEventListener子类放在哪里?



我想子类AbstractPersistenceEventListener这样我就可以在Grails 2.5.4中注册自定义事件侦听器。但是,我应该将这些子类放在哪里?

最重要的是,我希望这些事件侦听器使用自动连线的 bean,尤其是服务 bean。如果我将这些类放在src/groovy中,似乎我将不得不在resources.groovy中手动注册 bean,这是我想避免的额外步骤。

这篇文章展示了如果您不使用插件,如何在 grails 中注册自定义事件侦听器,您可以在闭包中注册它doWithApplicationContext而不是在Bootstrap.groovy中注册它。

你应该把这些类放在src/groovy下。不,您无需在resources.groovy中再次将侦听器注册为 bean 或任何其他 bean 。但是,如果您的侦听器需要使用任何 bean,那么您可以为其声明一个字段并在注册侦听器时对其进行初始化。例如,如果您需要在侦听器中注入grailsApplicationbean,请在注册侦听器时执行此操作:

def grailsApplication
def init = { servletContext ->
def applicationContext = servletContext.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT)
applicationContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
GormEventListener listener = new GormEventListener(datastore)
listener.with{
application = grailsApplication
}
applicationContext.addApplicationListener(listener)
}

最新更新