Using properties in Maven

Maven allows us to define as well as use properties. Properties allow us to avoid hardcoding values in multiple places such as versions of dependencies. They also provide flexibility to the build tool by allowing values to be passed at runtime.

How to do it...

Let's define and use Maven properties by performing the following steps:

  1. Open the pom file of a project that we created earlier.
  2. Define a property:
    <properties>
        <junit.version>3.8.1</junit.version>
    </properties>
  3. Use the property:
    <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>${junit.version}</version>
          <scope>test</scope>
        </dependency>

How it works...

There are different types of properties. They are as follows:

  • Environment variables: Prefixing a variable with env. will return the value of the shell's environment variable. For example, ${env.PATH} will return the value of the PATH variable.
  • pom variables: Prefixing a variable with project. will return the value of that element in the pom file. For example, ${project.version} will return the value in the <version> tag of the pom file.
  • The settings variable: Prefixing a variable with settings. will return the value of that element in the settings file. For example, ${settings.offline} will return the value <offline> in the settings file.
  • Java properties: Any property available through the System.getProperties() method in Java is available. For example, ${java.home}.
  • Normal properties: Values that are specified in the <properties> tag, which is shown in the following example:
    <properties>
      <java.version>1.7</java.version>
    </properties>

    Here, the ${java.version} command will return 1.7

Do remember that properties and profiles can break the portability of the project. Two specific practices for looking up in problem areas are as follows:

  • External properties: These are properties defined outside the pom file (in a settings file) but used as part of a plugin configuration. The absence of this property definition will break the build.
  • Incomplete specification: This is where properties are defined for different build environments. A missing definition for one will break the build.

See also

  • The Specifying source encoding for platform-independent builds recipe in this chapter.
..................Content has been hidden....................

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