Maven resource filtering and build profiles 

Joined:
08/13/2009
Posts:
172

December 06, 2011 19:52:15    Last update: December 06, 2011 19:52:15
Resource files under the src/main/resources directory are copied verbatim to the target/classes directory during build. But resources can be filtered by turning on filtering in pom.xml:
<build>
      <resources>
	<resource>
	    <directory>src/main/resources</directory>
	    <filtering>true</filtering>
	</resource>
      </resources>
</build>

When filtering is turned on, constructs like ${...} are replaced with actual values if they are defined. For example, create a file test.properties:
project.stage=${project.stage}

The build command "mvn package" simply copies test.properties to target/classes/. But if you build with:
mvn -Dproject.stage=dev package

the contents of target/classes/test.properties becomes:
project.stage=dev


Sometimes you want different resource definitions for different environments, e.g., dev vs. prod. You can achieve that by defining profiles in pom.xml:
<profiles>
	<profile>
	    <id>dev</id>
	    <properties>
		<project.stage>Development</project.stage>
	    </properties>

	    <activation>
		<activeByDefault>true</activeByDefault>
	    </activation>
	</profile>

	<profile>
	    <id>prod</id>
	    <properties>
		<project.stage>Production</project.stage>
	    </properties>
	</profile>
</profiles>

In the above, dev is the default profile, prod is defined but not active unless you specifically activate it. With the above profile:
  1. the command "mvn package" changes the contents of target/classes/test.properties to:
    project.stage=Development
    

  2. if you activate the prod profile with "mvn -P prod package", the contents of target/classes/test.properties becomes:
    project.stage=Production
    

  3. system properties overrides values defined in profiles. The command "mvn -Dproject.stage=dev package" creates target/classes/test.properties with contents:
    project.stage=dev
    

  4. You can active both dev and prod profiles with:
    mvn -P dev,prod package
    

    but what will the output be?

You can check active profiles with:
mvn help:active-profiles

Share |
| Comment  | Tags