2009-10-28 99 views
2

我的应用程序需要知道可以存储其数据的目录的路径。我尝试设置一个Java系统属性,并将该变量用作Spring XML中的占位符。使用Maven在Spring XML中无法解析系统属性

在Eclipse中,我将该属性添加到我的运行配置的环境中,它工作得很好。 Spring将$ {dataDir}解析为正确的路径。

但是,当我使用Maven2测试应用程序(mvn test -DdataDir = c:/ data)时,Spring抱怨它无法解析占位符。

我的春天XML看起来是这样的:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 

xmlns:tx="http://www.springframework.org/schema/tx" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd"> 

<!-- Allows me to use system properties in this file --> 
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" /> 

<bean id="xmlConfiguration" class="org.apache.commons.configuration.XMLConfiguration"> 
    <constructor-arg index="0"> 
    <value>${dataDir}/conf/config.xml</value> 
    </constructor-arg> 
</bean> 
</beans> 

为什么不说,系统属性传递给春天吗?我究竟做错了什么?感谢您的任何建议!

编辑:当然,你是对的:$ {baseDir}应该是$ {dataDir}。但这只是这个问题的一个错误,而不是真正的代码。

我试图MAVEN_OPTS之前,但要么...

+1

应该是baseDir,而不是数据目录 – toolkit 2009-10-28 15:23:26

+0

工具包,是的,我认为是。 – 2009-10-28 15:35:59

回答

4

这是Surefire插件2.4.3中的一个已知错误。有关详细信息,请参阅JIRA问题“System properties set on the command line get clobbered”。使用以前的版本,2.4.2改为:

<build> 
    <plugins> 
    <plugin> 
     <groupId>org.apache.maven.plugins</groupId> 
     <artifactId>maven-surefire-plugin</artifactId> 
     <!-- Use 2.4.2 because 2.4.3 has bug with system properties 
      see http://jira.codehaus.org/browse/SUREFIRE-121 --> 
     <version>2.4.2</version> 
    </plugin> 
    </plugins> 
</build> 
1

也许MVN测试不通过它与运行的测试系统性能它不工作?是否有可能使用测试插件传递属性(本身可能会将它们从系统属性中拉出来)?

参见:http://maven.apache.org/maven-1.x/plugins/test/properties.html

+0

这是最好的解决方案 - 在您的POM文件中嵌入任何必需的属性。通过这种方式,它们与项目一起存储,以便所有团队成员都可以访问它们(并且不必单独设置它们的env),因此它们受版本控制。 – 2009-10-29 18:29:50

0

如果你看一下mvn脚本,你可以看到,通过命令行传递的所有参数作为参数传递给推出类,而不是作为参数传递给JVM。所以-D将无法​​正常工作。

最快的解决方法是定义MAVEN_OPTS环境变量,例如,

set MAVEN_OPTS="-DdataDir=c:/data" 

,然后运行mvn test

+0

我认为这不再是事实。所选答案中最新添加的与JIRA相关的问题显示:“通过MAVEN_OPTS直接传递到JVM的系统道具不会转发到测试。” – Patrick 2010-11-04 23:16:55

0

可能是你应该使用相同的变量名?我的意思是你传递dataDir,但期望baseDir。我错了吗?

0

我认为flicken的answer是正确的回答你的问题。

但是,我建议将​​3210文件移动到src/test/resources。这似乎是一个完美的位置(在Maven的世界),这样,文件将在类路径中可用(所以你不必使用绝对路径)。最重要的是,该文件最终会像版本控制中的任何其他资源一样,这是一件好事。

如果真的要将它保留在项目结构之外,我会使用resources filtering来过滤您的Spring配置文件并在构建时设置${dataDir}

+0

该文件应该存储在项目之外,因为当我想更新应用程序时,它不能被覆盖。但将它保留在版本控制下是一个很好的观点。必须考虑这一点 – Olvagor 2009-11-03 12:18:40