Maven 常用参数之:Java 源文件编码、-source 和 -target 参数

最近在做的项目是用 Maven 进行打包,目前遇到如下两个问题,记录起来备忘:

1. Java 源文件编码问题

在 Maven 的打包日志中看到如下内容:

[WARNING] Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!

看信息的意思就是说它取了系统默认的 GBK 编码,于是 Google 了一下“Maven encoding”,找到 官方 FAQ 了,解决办法是在工程的 pom.xml 中添加如下内容:
<project>
  ...
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  ...
</project>

2. 编译版本问题

编译时报如下错误:

[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] AAA\.jenkins\workspace\BBB\CCC.java:[73,46] 错误: -source 1.5 中不支持 diamond 运算符
[ERROR]   (请使用 -source 7 或更高版本以启用 diamond 运算符)
[ERROR] AAA\.jenkins\workspace\BBB\DDD.java:[38,33] 错误: -source 1.5 中不支持 lambda 表达式
[ERROR]   (请使用 -source 8 或更高版本以启用 lambda 表达式)

奇怪的是我的 Jenkins 构建机器上只安装了 JDK 8,为什么还会说不支持 diamond 和 lambda 呢?在 Google 大神的指引下,在 Maven Compiler 插件介绍 里面找到了答案:Also note that at present the default source setting is 1.5 and thedefault target setting is 1.5, independently of the JDK you run Maven with.

原来 Maven Compiler 插件默认会加 -source 1.5 及 -target 1.5 参数来编译(估计是为了兼容一些比较老的 Linux 服务器操作系统,它们通常只有 JDK 5),而我们的代码里使用了 JDK 7/8 的语法。解决办法在这里

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

3. 单元测试问题

开发人员在代码里加了一些单元测试代码,但由于 Jenkins 构建环境没有相应的访问权限(如 Redis 服务器做了限制),会导致这些测试执行失败。于是也在这里找到了跳过测试的办法:加 -DskipTests 或 -Dmaven.test.skip=true 参数运行 Maven。

因为我的 SVN 用户只有测试人员权限,无法提交代码来修改 pom.xml,于是我给 maven 加了如下参数来实现上述目的:-Dmaven.test.skip=true -Dmaven.compiler.source=1.8 -Dmaven.compiler.target=1.8 -Dmaven.compiler.encoding="UTF-8"

转载地址:http://ju.outofmemory.cn/entry/155158


发布了267 篇原创文章 · 获赞 66 · 访问量 43万+

猜你喜欢

转载自blog.csdn.net/shenfuli/article/details/66971944