Marty Pitt
Marty Pitt

Reputation: 29290

Groovy conventions: Where do I put metaClass definitions?

I'm starting to add some Groovy classes to an existing Java web app. (This is not a Grails app)

Is there a convention I should follow as to where I define my metaClass extensions?

Also, I've written a handful of extensions for assisting with unit tests. Currently, these sit in the @Before of the base class for the tests, but I suspect there's a more obvious place I should be setting these up.

Any advice greatly appreciated.

Upvotes: 3

Views: 233

Answers (2)

Benjamin Muschko
Benjamin Muschko

Reputation: 33436

Another option is to use Groovy's naming convention for custom MetaClasses. As long as you stick to the convention (groovy.runtime.metaclass.[package].[class]MetaClass) and you compile the code with your application code you should be fine. Check this posting for more information. It also provides a good example.

Upvotes: 5

Benjamin Muschko
Benjamin Muschko

Reputation: 33436

If it would have been a Grails app I'd say put it in grails-app/conf/BootStrap.groovy. In any other Java web application you could simply write a ServletContextListener implementation which triggers on web context initialization and destruction. Register the Listener in your web.xml.

public class MetaClassInitializationListener implements ServletContextListener {
   public void contextInitialized(ServletContextEvent event) {
      // do metaClass work
   }

   public void contextDestroyed(ServletContextEvent event) {
   }
}

For the unit tests a base class sounds reasonable to me. If you're using JUnit you could also write an implementation of BlockJUnit4ClassRunner. You can then pick and choose to which unit test you want to apply your extensions using the @RunWith annotation.

Upvotes: 0

Related Questions