【发布时间】:2016-04-07 02:41:58
【问题描述】:
我有混合 Java/Scala 项目,我使用 Maven 作为构建工具,并且我的项目版本在 pom.xml 文件中提到:
<parent>
<groupId>com</groupId>
<artifactId>stuff</artifactId>
<version>3.6.7.7-SNAPSHOT</version>
</parent>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>scala-compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
我想在我的scala代码中使用项目版本(3.6.7.7-SNAPSHOT),这意味着我需要在编译过程中以某种方式注入它,有什么办法吗?
已经尝试使用getProperty函数-
val properties = System.getProperties()
override def version: String = properties.get("parent.version")
但它返回 null。
edit-我发现了一个类似的 question 用于 Java 代码。
我决定使用maven-replacer-plugin
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>maven-replacer-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<file>.\src\main\resources\Installer.scala</file>
<outputFile>.\src\main\scala\com\Installer.scala</outputFile>
<replacements>
<replacement>
<token>@pomversion@</token>
<value>${project.version}</value>
</replacement>
</replacements>
</configuration>
</plugin>
但缺点是我必须在资源目录中创建一个新文件,有什么办法可以在编译后将类恢复到原始状态,即使编译失败?
已解决-
我将正则表达式与maven-replacer-plugin 一起使用,位于定义版本变量的行并使用 -
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>maven-replacer-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<file>.\src\main\scala\com\Installer.scala</file>
<outputFile>.\src\main\scala\com\Installer.scala</outputFile>
<replacements>
<replacement>
<token>override def version: String = (.*)</token>
<value>override def version: String = "${project.version}"</value>
</replacement>
</replacements>
</configuration>
</plugin>
使用此方法,变量会根据正确的版本更改每次构建,而无需向项目添加新文件。
【问题讨论】: