Maven profiles are a way to define a set of configuration options for a Maven build. Profiles are used to specify different build configurations for different environments or situations. For example, you may have a development profile that uses a local database for testing and a production profile that uses a remote database.
Profiles can be activated in several ways, including by specifying a command-line option, by setting an environment variable, or by configuring the POM file. When a profile is activated, it can modify the behavior of the build by adding or removing dependencies, setting properties, or executing specific goals.
Here’s an example of a profile definition in a POM file:
<profiles> <profile> <id>development</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <database.url>jdbc:mysql://localhost/mydb_dev</database.url> </properties> <dependencies> <dependency> <groupId>com.example</groupId> <artifactId>myapp-dev-utils</artifactId> <version>1.0.0</version> </dependency> </dependencies> </profile> <profile> <id>production</id> <properties> <database.url>jdbc:mysql://prod-db-server/mydb_prod</database.url> </properties> </profile> </profiles>
In this example, there are two profiles defined: “development” and “production”. The “development” profile is activated by default and sets the database URL property to a local development database. It also includes a dependency on a utility library for development purposes. The “production” profile sets the database URL property to a production database.
Profiles can be very useful for managing different build configurations in a flexible and customizable way.
You can use Maven profiles in different ways with the
mvn command. Here are a few examples:
- To activate a specific profile during the build process, you can use the
-Poption followed by the profile ID. For example, to activate the “production” profile from the example in the previous answer, you can run:
mvn clean install -Pproduction
This will activate the “production” profile and configure the build accordingly.
- You can also activate multiple profiles at once by separating their IDs with commas. For example:
mvn clean install -Pdevelopment,debug
This will activate the “development” and “debug” profiles at the same time.
- If you have defined a default profile in your POM file, you can activate it without specifying its ID by using the
-Dmaven.profiles.defaultoption followed by
true. For example:
mvn clean install -Dmaven.profiles.default=true
This will activate the default profile, if one is defined in the POM file.