Groovying on Template Aid for Java

23 / Dec / 2021 by Sumit Navin 0 comments

If you haven’t combined Groovy scripts with your Java projects yet, you’re missing out. It’s super easy with Maven, and it’ll make your code more modular and elegant. But most importantly, you’ll have some fun scripting, and if nothing else, you’ll most certainly benefit from some of the grooviest features, including the magic that is Groovy’s GString!

You can check out the code for this tutorial in GITHUB.

The given environment

Let’s say you have a service for connecting customers to representatives via some sort of messaging service. When the customer first reaches out to the service, he should be responded with a standard message (a template) that includes his name, his queue number, and an informational greeting of some sort.

Groovy scripting

Create a file as a template for your messages.

  • The def statements allow us to bind arguments from the shell.
  • The """ marks the text as a GString, which allows us, in this case to:
    • Easily incorporate the arguments with no String.format required.
    • Produce multi-line strings without worrying about line breaks and long lines.
  • What you might have noticed missing here, is the return statement. With Groovy the last statement is the return statement.

Now let’s invoke the script with some intentionally boiler plated Java code:

Can you see how easy it is to add arguments? Just add them to the script, and add the binding to the invoking class. No more “scratching your head” when it comes to concatenating long strings…
The real conundrum here is, how do we get the script in our class loader?

It’s easy with Maven, let’s say this is our project layout:

First, we need to include the groovy dependency.

Now we have the appropriate Groovy API classes like GroovyShell and Binding in our class loader.
We now need to add the following to our build section in our pom.xml:

This will add everything from our src/scripts folder to our class loader under the folder scripts.
So we’ll be able to find our script like so: scripts/create_message.groovy.

Java: Bi-function applying

This is fine and good to use too, just that there will be big long constant strings in your code.

 

FOUND THIS USEFUL? SHARE IT

Tag -

Groovy Java

Leave a Reply

Your email address will not be published. Required fields are marked *