Maven Build Profiles

 

In Maven, a Build Profile is a way to customize the build process for different environments, configurations, or deployment targets. Profiles allow you to specify certain build settings (like dependencies, plugins, properties, and goals) that should be used only in specific conditions — for example, development, testing, or production environments.


Why Use Build Profiles?

You might want to:

  • Use different databases for dev and prod

  • Deploy to different servers based on environment

  • Include/exclude certain modules

  • Set environment-specific properties (example: API keys, credentials, etc.)


Where Are Profiles Defined?

  • In pom.xml file — most common place
  • In ~/.m2/settings.xml — for user-specific configuration
  • From command line — when triggering a build



Basic Syntax in pom.xml


<project>
  ...
  <profiles>
    <profile>
      <id>dev</id>
      <properties>
        <env.name>Development Environment</env.name>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
    </profile>

    <profile>
      <id>prod</id>
      <properties>
        <env.name>Production Environment</env.name>
      </properties>
    </profile>
  </profiles>
</project>

You can then use ${env.name} anywhere in your pom.xml.



Activating Profiles

 - From Command Line:

mvn clean install -Pdev
mvn clean install -Pprod

      


 - Automatically with Activation Block:


<activation>
  <property>
    <name>env</name>
    <value>prod</value>
  </property>
</activation>



  - By OS, JDK, or File Presence:
  • You can also activate profiles based on:
  • Operating System

  • JDK version

  • Presence of a file or environment variable




Example:


<profiles>
  <profile>
    <id>qa</id>
    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>


To activate this:

mvn clean install -Pqa

No comments:

Post a Comment