views:

27

answers:

1

Hi,

I have some custom groovy classes in my Grails project, and I would like to inject a logger and some other stuff into the class, like it works in a Service class or Controller class. The code in the "target" class would in this way have direct access to logging without further ado.

How would it be possible to write scripts to hook into events in the "doWithDynamicMethods" style in a Grails project (as opposed to a Grails Plugin) and in this way enhance your own classes?

Thanks,

Christian Sonne Jensen

A: 

In an application, typically you would do this in grails-app/conf/BootStrap.groovy, e.g.

class BootStrap {

   def init = { servletContext ->
      Foo.metaClass.getLog = { -> ... }
   }
}
Burt Beckwith
Hi, It is true that you can do that, but I know it can be done with a script. Somehow I like the idea better when enhancement is placed in a script. I once saw it in relation to the Tomcat plugin how add stuff to the web.xml. Unfortunately I cannot fint that example at the moment.
Adding elements to web.xml is quite different from adding metaclass methods to classes. There's no support for a 'doWithDynamicMethods' phase in a regular Grails application like there is in a plugin, but there doesn't need to be one. A plugin needs a hook to register Spring beans and to alter web.xml since that has to happen early in the startup process, but you can add metaclass methods any time. So BootStrap is as good a place as any.
Burt Beckwith