问题
I want to subclass AbstractPersistenceEventListener
so I can register custom event listeners in Grails 2.5.4. However, where should I place these subclasses?
Most importantly I want these event listeners to use autowired beans, especially service beans. If I put these classes in src/groovy, it seems I'll have to manually register the beans in resources.groovy, which is an extra step I'd like to avoid.
回答1:
This post shows how you can register a custom event listener in grails if you are not doing it using a plugin where you can register it inside doWithApplicationContext
closure instead of doing it inside Bootstrap.groovy
.
And you should put these classes under src/groovy. And no, you don't need to register the listener as a bean or any other beans again inside resources.groovy
. However if your listener need to use any bean then you can declare a field for that and initialize it when you are registering the listener. For eg if you need to inject grailsApplication
bean in your listener then do this while registering your listener:
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)
}
来源:https://stackoverflow.com/questions/38043214/where-to-put-abstractpersistenceeventlistener-subclasses-in-grails-2-5-4