Scala类无法获取Maven process-exec插件设置的JVM系统属性
问题描述
我在使用com.bazaarvoice.maven.plugins:process-exec-maven-plugin(版本0.7)时碰到了一个头疼的问题:需要在pre-integration-test阶段启动Scala编写的服务发现Mock,通过-DENDPOINTS和-DPORT传递系统属性,但在Mock的启动类MockBootable里,用sys.props获取这些属性时,总是只能拿到默认值。
我的Scala代码片段如下:
println("************** PROPERTIES *****************") sys.props.foreach(entry => { println(s"${entry._1} -> ${entry._2}") }) val port = sys.props.getOrElse("PORT", "666").toInt var path = sys.props.getOrElse("ENDPOINTS", null)
解决方案
折腾了一阵才找到问题根源:JVM的系统属性参数(-D开头的)必须放在主类名称之前,否则JVM不会把这些参数识别为系统属性,而是当成主类的命令行参数处理。
调整后的Maven插件配置如下:
<plugin> <groupId>com.bazaarvoice.maven.plugins</groupId> <artifactId>process-exec-maven-plugin</artifactId> <version>0.7</version> <executions> <execution> <id>Start-Service-discovery-Mock</id> <phase>pre-integration-test</phase> <goals> <goal>start</goal> </goals> <configuration> <skip>${skipStartService}</skip> <name>start-service-discovery-mock</name> <arguments> <argument>java</argument> <argument>-XX:+HeapDumpOnOutOfMemoryError</argument> <argument>-Xmx512M</argument> <argument>-Xms256M</argument> <argument>-Xss1M</argument> <argument>-XX:+UseParallelGC</argument> <argument>-cp</argument> <argument> service-${project.version}.jar${path.separator}../../f2e-mock-service/target/lib/* </argument> <argument>-DENDPOINTS=${project.build.directory}${path.separator}classes${path.separator}service-discovery${path.separator}endpoints.conf </argument> <argument>-DPORT=8600</argument> <argument>mocks.bootables.MockBootable</argument> </arguments> </configuration> </execution> </executions> </plugin>
注意看,-DENDPOINTS和-DPORT这两个参数被放在了主类mocks.bootables.MockBootable的前面,这样JVM就能正确识别并加载这些系统属性,Scala代码里的sys.props也能读到对应的值了。
内容的提问来源于stack exchange,提问作者paul
相关产品推荐
相关产品推荐

