<-- home

Embedding Groovy scripts into your Java application

I like Groovy for a lot of things like being easy to learn, its dynamic feature, readable syntax etc. But one of the things I like and utilize most is its embedding feature which helps you to run Groovy scripts in your already-running Java application. If you have a stateful Java application, running arbitrary Groovy scripts to examine your state can be very useful when things screw up on run-time.

Groovy’s embedding feature is quite smooth and painless. We tried Mozilla’s Rhino before Groovy and I could not warm up to that. It seemed too complex to me. But when I tried Groovy, it took a few minutes to run a Groovy script in the application. I just added a few dependencies, initiated a couple of classes and provided the script.

Groovy guys have explained how you can embed Groovy into your application on this page with different methods. I prefer the GroovyShell class. Using Binding instance, I can pass objects I want to access from the script. If you are using a IoC container like Spring, you can pass your ApplicationContext, or you just pass a couple of service classes, or any other classes you want to make use of.

It may be useful to catch the output of the script. To do that, you can pass an object like StringWriter via Binding and use that object instance for writing output.