我已将一个项目从 Eclipse 移植到 Maven,我需要设置一个环境变量以使我的项目正常工作。
在 Eclipse 中,我转到
Run -> Run configurations
,然后在选项卡 environment
下,将 WSNSHELL_HOME
设置为值 conf
。
如何使用 Maven 做到这一点?
您可以在命令行上传递它,如
mvn -DmyVariable=someValue install
[更新]请注意,参数的顺序很重要 - 您需要在命令之前指定任何选项。[/更新]
在 POM 文件中,您可以将系统变量(在命令行或 pom 中指定)称为${myVariable}
,将环境变量称为
${env.myVariable}
。(感谢评论者指正。) 更新2
Surefire 插件 进行测试,最好是在 pom 中的 plugins
部分指定所需的系统变量,例如
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
...
<configuration>
...
<systemPropertyVariables>
<WSNSHELL_HOME>conf</WSNSHELL_HOME>
</systemPropertyVariables>
</configuration>
</plugin>
...
</plugins>
</build>
-D
属性不会可靠地从surefire-pluging传播到您的测试(我不知道为什么它与eclipse一起工作)。在命令行上使用 Maven 时,请使用argLine 属性来包装您的属性。这将使它们通过您的测试
mvn -DargLine="-DWSNSHELL_HOME=conf" test
使用
System.getProperty
读取代码中的值。看看this 帖子,了解
System.getenv
和
Sytem.getProperty
的区别。
#!/bin/bash
export YOUR_VAR=thevalue
mvn test
unset YOUR_VAR
http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#environmentVariables http://maven.apache.org/surefire/maven-failsafe-plugin/integration-test-mojo.html#environmentVariables
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
...
<configuration>
<includes>
...
</includes>
<environmentVariables>
<WSNSHELL_HOME>conf</WSNSHELL_HOME>
</environmentVariables>
</configuration>
</plugin>
MAVEN_OPTS
(或 Windows 上的
${user.home}/.mavenrc
)中设置
%HOME%\mavenrc_pre.bat
(或其他环境变量)。自 Maven 3.3.1 起,有
设置 mvn 命令行参数的新可能性,如果这是您真正想要的:
${maven.projectBasedir}/.mvn/maven.config
${maven.projectBasedir}/.mvn/jvm.config
properties-maven-plugin 的 Maven 插件,它提供了一个目标 set-system-properties
来设置系统变量。如果您有一个包含所有这些属性的文件,这尤其有用。因此您可以读取属性文件并将它们设置为系统变量。
System.getProperty("WSNSHELL_HOME")
mvn clean test -DargLine=-DWSNSHELL_HOME=yourvalue
如果您想在 Eclipse 中运行它,请在调试/运行配置中添加 VM 参数
-DWSNSHELL_HOME=你的值
不需要修改POM
_JAVA_OPTIONS
变量传递一些参数。例如,为 Maven 代理标志定义一个变量,如下所示:
_JAVA_OPTIONS="-Dhttp.proxyHost=$http_proxy_host -Dhttp.proxyPort=$http_proxy_port -Dhttps.proxyHost=$https_proxy_host -Dhttps.proxyPort=$http_proxy_port"
然后使用mvn clean install
(它会自动拾取
_JAVA_OPTIONS
)。
direnv。有了它,您可以在 cd 进入项目后注入环境变量。这些步骤对我有用:
.envrc 文件
source_up
dotenv
.env 文件
_JAVA_OPTIONS="-DYourEnvHere=123"
_JAVA_OPTIONS 是一个坏主意。相反,定义 MAVEN_OPTS 环境变量,它仍然会被 Maven 自动选取,但它不会像 _JAVA_OPTS 那样覆盖所有内容(例如 IDE 虚拟机选项)。
MAVEN_OPTS="-DmyVariable=someValue"