最近讓不同JAVA版本的容器maven打包折騰的不行,終於理出了一點頭緒。在這里記錄下備忘。
1. Maven與jdk版本的關系
先明確一個概念,關高版本JDK運行maven,是可以打出低版本的JAVA目標二進制文件的。比如用jdk 1.8運行maven,可以編譯1.8,1.7.1.6等的代碼,並輸出相應版本的二進制文件。
當然,用低版本的jdk運行maven,是不可能輸出高版本的JAVA二進制文件的。
另外:maven用哪個版本的JDK運行,取決於環境變量JAVA_HOME指向的是哪個版本。
2. 如何用Maven打出不同版本的JAVA二進制文件
我們可以在項目內的pom.xml和全局配置setings.xml內配置:
2.1 項目內的pom.xml內定義:
<build>
<finalName>test-project</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
上面的配置就定義了通過jdk 1.8來構建
2.2 maven全局配置文件
在maven全局配置文件conf/settings.xml內配置:
<settings>
<profile>
<profile>
<id>jdk-1.8</id> <!-- profile 名 -->
<activation>
<activeByDefault>false</activeByDefault> <!-- 此profile是否活動 -->
<jdk>1.8</jdk> <!-- jdk版本 -->
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</profile>
<profile>
<id>jdk-1.7</id>
<activation>
<activeByDefault>false</activeByDefault>
<jdk>1.7</jdk>
</activation>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.compilerVersion>1.7</maven.compiler.compilerVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>jdk-1.7</activeProfile> <!-- 這個參數是定義活動的profile -->
</activeProfiles>
</settings>
上面的配置是通過定義根據使用不同的jdk來選擇不同的打包方案。
那么定義的profile如何使用呢?可以使用-P參數來指定。mvn package -P jdk-1.7
3. 全局配置中profile的激活
3.1 使用activeByDefault激活
<id>jdk-1.7</id> <activation> <activeByDefault>false</activeByDefault> <jdk>1.7</jdk> </activation>
3.2 使用activeProfiles激活
<activeProfiles>
<activeProfile>jdk-1.7</activeProfile> <!-- 這個參數是定義活動的profile -->
<activeProfile>jdk-1.8</activeProfile>
</activeProfiles>
當定義了多個profile為激活的時候,它是根據profile定義的先后順序來進行覆蓋取值的,然后后面定義的會覆蓋前面定義的。
3.3 使用-P參數激活
使用-P參數來激活。mvn package -P jdk-1.7
4. profile的生效順序
全局配置setting.xml內定義的激活的profile會優先於項目內的pom.xml。
- 如果maven setting.xml 配置
<activeByDefault>true</activeByDefault>,並且pom中maven-compiler-plugin 未指定版本則優先生效; - 如果maven setting.xml 配置
<activeByDefault>false</activeByDefault>,並且pom未指定target,則根據環境變量JAVA_HOME生效; - 如果 pom.xml 中的 maven-compiler-plugin 指定版本則優先生效;
- maven(ver 3.3.x)默認target 版本是1.6;
- 運行的maven 的 JAVA_HOME 版本要 >= 生效的target版本;
- 可以使用
mvn help:active-profiles來查看哪些profile處於激活狀態
5. 包依賴問題
有時候經常會發生包不對的問題,可以用以下命令查看項目的包依賴。mvn dependency:tree
