Filtering Source Files using the Templating Maven Plugin

September 3rd, 2013 by

The Templating Maven Plugin looks useful if one needs to copy and to filter source files in a project e.g. to add property values from the build environment to a class.

For a short demonstration I’ve added the following short snippet.


 

Dependencies

Only one dependency needed .. simply add the following snippet to your pom.xml

<build>
	<plugins>
		<plugin>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>templating-maven-plugin</artifactId>
			<version>1.0-alpha-3</version>
			<executions>
				<execution>
					<id>filter-src</id>
					<goals>
						<goal>filter-sources</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>

Example Class

This is a sample class that should be enriched with environment variables from the Maven lifecycle .. just put it in src/main/java-templates

We’re using variables to specify the artifactId, groupId, version from the pom.xml and project’s build directory here..

package com.hascode.tutorial;
 
public class Main {
	public static void main(String[] args){
		System.out.println("Templating Plugin for Maven Example");
		System.out.println(String.format("artifactId: ${project.artifactId}, groupId: ${project.groupId}, version: ${project.version}"));
		System.out.println("project build directory: ${project.build.directory}");
	}
}

Building and Running

Build and run using the following commands:

mvn package
java -cp target/templating-maven-plugin-example-0.0.1.jar com.hascode.tutorial.Main

This should produce the following output (the build directory possibly differs ;)

Templating Plugin for Maven Example
artifactId: templating-maven-plugin-example, groupId: com.hascode.tutorial, version: 0.0.1
project build directory: /data/project/templating-maven-plugin-example/target

Tutorial Sources

Please feel free to download the tutorial sources from my Bitbucket repository, fork it there or clone it using Git:

git clone https://bitbucket.org/hascode/templating-maven-plugin-sample.git

Resources

Tags: , , , ,

One Response to “Filtering Source Files using the Templating Maven Plugin”

  1. John Carlson Says:

    I’d like to replace a generic class name ‘NeedClassHere’ with the actual class from the Java filename. Can’t find the maven property for it though. Any ideas?

Search
Categories