Maven Resources Filtering

There are times when we want to use some parameters that can be only specified during compile time. A fine way of implementing this is via Maven’s resources tag and the place is in the POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.dimitrisli.maven</groupId>
	<artifactId>MavenResourcesFiltering</artifactId>
	<version>1.0</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<build>

		<finalName>MavenResourcesFiltering</finalName>

		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>${project.build.sourceEncoding}</encoding>
				</configuration>
			</plugin>
		</plugins>

	</build>
</project>

notice in particular the resources tag:

                 <resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>

The default filtering value for this directory is false so we need to override it switching filtering to true. This basically will scan the directory and search for ${} entries referring to POM properties or entries. All this is happening during compile time.

Say for instance we have a project.properties in /src/main/resources with the following entry:

${project.artifactId}
${project.version}
${project.build.sourceEncoding}

then after compilation in the produced jar we will find:

MavenResourcesFiltering
1.0
UTF-8
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s