Filtering using resources

Now, let us see how we can put the resources features of Maven to good use, that is, to perform variable replacements on project resources. This feature is useful when you need to parameterize a build with different configuration values, depending on the deployment platform.

You can define variables in your resources. Let us see how we can get the value of these variables from properties, resource filter files, and the command line.

How to do it...

To perform filtering using resources, use the following steps:

  1. Add a property with a variable in the src/main/resource/app.properties file:
    display.name=Hello ${project.name}
  2. Add the following code in the pom file:
      <build>
        <resources>
          <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
          </resource>
        </resources>
      </build>
  3. Invoke the process-resources phase:
    mvn process-resources
    
  4. Examine the processed resource app.properties in target/classes:
    C:projectsapache-maven-cookbookproject-with-resource-filtering	argetclasses>type app.properties
    display.name=Hello Project with resource filtering
    

How it works...

In the Using properties in Maven recipe of Chapter 3, Maven Lifecycle, we saw the various types of properties that Maven can have. In the preceding case, we set the filtering element to true. Maven replaced the variable ${project.name} with the property value corresponding to the name of the project defined in the pom file, namely Project with resource filtering.

There's more...

You can override the property values from the command line:

mvn –Dproject.name="Override from command line" process-resources

Now, look at app.properties by navigating to target/classes:

C:projectsapache-maven-cookbookproject-with-resource-filtering>type targetclassesapp.properties
display.name=Hello Override from command line

If you have a large number of variables whose values differ based on the environment, then you can create a file, say my-filter-values.properties, in the project codebase holding the keys and values (say, src/filter folder) and use them as filters:

<filters>
    <filter>my-filter-values.properties</filter>
</filters>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.188.201