Maven Profile is a mechanism provided by Maven to use different build configurations in different environments or conditions. Profile allows developers to define multiple sets of configurations and activate the corresponding configuration during the build based on conditions.
Profile Definition Locations:
- pom.xml: Project-level Profile, only valid for the current project
- settings.xml: User-level Profile, valid for all projects
- ~/.m2/settings.xml: Global-level Profile, valid for all users and projects
Profile Activation Methods:
- Command Line Activation: Use
-Pparameter to specify the activated Profile
bashmvn clean install -Pdev mvn clean install -Pdev,test
- Environment Variable Activation: Judge through environment variables
xml<profiles> <profile> <id>dev</id> <activation> <property> <name>env</name> <value>dev</value> </property> </activation> </profile> </profiles>
- JDK Version Activation: Automatically activate based on JDK version
xml<activation> <jdk>11</jdk> </activation>
- Operating System Activation: Automatically activate based on operating system
xml<activation> <os> <family>Windows</family> </os> </activation>
- File Existence Activation: Automatically activate based on whether a file exists
xml<activation> <file> <exists>src/main/resources/dev.properties</exists> </file> </activation>
Common Use Cases for Profile:
- Multi-environment Configuration: Use different configurations for development, testing, and production environments
xml<profiles> <profile> <id>dev</id> <properties> <env>dev</env> <db.url>jdbc:mysql://localhost:3306/dev</db.url> </properties> </profile> <profile> <id>prod</id> <properties> <env>prod</env> <db.url>jdbc:mysql://prod-db:3306/prod</db.url> </properties> </profile> </profiles>
- Dependency Management: Use different dependency versions in different environments
- Plugin Configuration: Use different plugin configurations in different environments
- Resource Filtering: Filter different resource files based on Profile
xml<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build>
Best Practices:
- Define clear Profile names for different environments (dev, test, prod)
- Use properties to uniformly manage environment-related configurations
- Define common Profiles in parent POM, which can be inherited by submodules
- Avoid defining too many configurations in Profile, keep it concise
- When activating multiple Profiles with
-Pparameter, pay attention to configuration priority - Use Profile to automate builds for different environments in CI/CD processes
Common Commands:
mvn help:active-profiles: View currently activated Profilesmvn help:all-profiles: View all available Profilesmvn clean install -Pprofile1,profile2: Activate multiple Profiles