Configuring Velocity Tools With Spring Boot

You can take several approaches to configuring Velocity Tools with Spring, some of which appear to be really simple and others which require lots of coding. We took a different approach in NixMash Spring which I hope you’ll agree gets points for originality. It’s definitely simple.

First, what ARE Velocity Tools? They’re a collection of libraries that add functionality to the Apache Velocity templates we use for Mail and NixMash Spring Post formatting, among other things. We just added tags to Nixmash Spring Posts and wanted to escape multi-word tags for cleaner urls. “Funky Town” becomes “funky+town.”

Velocity EscapeTools (along with a little Java .toLowerCase()) in our Velocity Template does the job with $esc.url(…). But to gain that functionality we need to of course configure Velocity Tools.

Velocity Tools Configuration Should Be Simple, But…

Configuring Velocity Tools with Spring should be simple…and maybe it is and I’m missing something. After all, look at the great IntelliJ intellisense support for configuring Velocity in application.properties, including the location of toolbox.xml, the required configuration file for Velocity Tools.

On top of that, Velocity Tools is baked-in to the Spring Boot Velocity Starter library we added to our build.gradle file.

On the other hand, an essential Spring Velocity Toolbox Configuration class in the Spring Boot Project is VelocityLayoutView which we see in the JavaDoc notes has been “@deprecated as of Spring 4.3 in favor of FreeMarker.”

The Essentials

Whatever the issues might have been, configuring Velocity Tools turned into something really hard, so it was time to look at our essential requirements. When we do that, we realize we want to add the Tools functionality in the model we’re sending to the template. That’s all we need. So instead of building a custom VelocityToolboxView class or add a bunch of beans, or even a toolbox.xml file, we asked what are our minimum configuration requirements and look to the Model object.

Here we’re creating a model to add a NixMash Spring Post object. Normally that Model is initialized as an empty HashTable.

Time to add Velocity Tools functionality.

We just added the Velocity Tools we needed with 2 lines of code. Actually, “math” is there for fun, so 1 line of code. Let’s look again at the template. $esc functionality good to go!

As a bonus, here is a list of the Velocity Tool libraries, so if you’re doing much with Velocity these libraries are a must.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.