views:

52

answers:

1

How would you structure Freemarker (or an alternative) as a templating code generator into a Maven project? I'm pretty new to Maven and would appreciate some help.

I want to generate some code from templates in my project. [a]

Rather than write my own, googling found freemarker which appears to be used by Spring which is a good enough reference for me, though as I haven't started with it yet, any other suggestions that work well with Maven would be appreciated too.

This website tells me how to add it as a dependency to my pom.xml. This SO question tells me where the generated sources should go. What I can't work out is how to tie it all together, so I get my generated sources generated from the templates, and then my generated sources used like regular sources for compile, test, jar, javadoc etc. Has anyone else used a template code generator for java within maven and could help?

[a] I know Generics would be the usual solution, and in fact I'm using them, but I have to use templates to cope with the primitive cases, without introducing copy/paste errors. Please trust me on this :-)

+2  A: 

I had written a maven plugin for this purpose. It uses the FreeMarker Pre Processor.

Heres the fragment from pom.xml highlighting its usage:

<plugins>
    <plugin>
        <configuration>
            <cfgFile>src/test/resources/freemarker/config.fmpp</cfgFile>
            <outputDirectory>target/test/generated-sources/fmpp/</outputDirectory>
            <templateDirectory>src/test/resources/fmpp/</templateDirectory>
        </configuration>
        <groupId>com.googlecode.fmpp-maven-plugin</groupId>
        <artifactId>fmpp-maven-plugin</artifactId>
        <version>1.0</version>
        <executions>
            <execution>
                <phase>generate-sources</phase>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>

Here the cfgFile is the path where you keep the config file for FMPP. (if you are not using any special data passing in FreeMarker then an empty file will be enough) templateDirectory is where you keep the FreeMarker templates. outputDirectory is where you want the output files to be generated.

I am in process of writing a detailed documentation highlighting the plugins usage and will update the project website accordingly.

Faisal Feroz
+1 for the plugin.
Adeel Ansari