{{announcement.body}}
{{announcement.title}}

Tutorial: Generating Java Files with Spring and Mustache

DZone 's Guide to

Tutorial: Generating Java Files with Spring and Mustache

If you need to generate complex model from a large source data, you should try this

· Java Zone ·
Free Resource

In this tutorial, we are going to use Spring Boot and Mustache to generate a model using a given set of data.

The data was extracted from a rules and validation table. Here's a quick explanation of how it works — we receive a request with SOAP, and we validate its structure by reading this data, for example, what type of request it is and we transform each field if necessary. The problem appears when there are many requests that we have to validate, so we need to generate and adapt a specific object for each type of request.

In this tutorial, we will create our model from a source file called data.txt, generating java files with properties and annotations in a Builder pattern structure

1. Create a Spring Boot Project in https://start.spring.io

In this tutorial, we don't need any additional dependencies except for the defaults dependencies.

Spring Initializr


2. Add the Mustache Java Library in the pom.xml File

This library works with Java 8:

XML
 




x


1
<dependency>
2
            <groupId>com.github.spullara.mustache.java</groupId>
3
            <artifactId>compiler</artifactId>
4
            <version>0.9.6</version>
5
</dependency>



 3. Create a Template for the Class (Builder Pattern)

Here the Mustache manual https://mustache.github.io/mustache.5.html 

Java


4. Create a Context Class to Adapt the Given Data to the Template

In this tutorial, we need a simple class that matches the template property names

Java


5. Read and Transform the Data to the Context Class

Java


6. Examine the Generated Objects

You can run several times until you get the Java files correctly

Here's the output:

Models generated

Here's a generated Java file:

Java


Conclusion

There are situations when it becomes very repetitive to write a complete and complex model in a migration or a new implementation, and maybe  the definition of each file can be structure in a source data. This is very useful and can save a lot of time.

Here the source code: https://github.com/farvher/modelgenerator 

Topics:
generate files, java, mustache, spring, tutorial

Published at DZone with permission of Farith Sanmiguel . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}