无法在persistence.xml中读取环境变量

时间:2013-06-11 12:52:28

标签: environment-variables eclipselink maven-3 persistence.xml maven-tomcat-plugin

我有一个Maven3项目,我正在使用tomcat7-maven-plugin。我想通过jvm的环境变量参数设置嵌入式数据库的路径。

在Java-Method中使用System.getenv(“myDataDir”)读取变量将返回正确的路径。 但是当我尝试在我的persistence.xml中设置变量$ {myDataDir}然后我用“mvn tomcat:run”启动tomcat时,我得到了FileNotFoundExceptions,因为变量没有被实际值替换(它表示例如找不到路径$ {myDataDir} \的derby.log)

我不知道造成这种情况的原因 - 如果它是持久性提供程序(EclipseLink)不支持这个或者它是其他东西。

我的persistence.xml如下所示:

<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
  <persistence-unit name="myPersistence" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:${myDataDir}/DB;create=true;upgrade=true" />
      <property name="javax.persistence.jdbc.user" value="admin" />
      <property name="javax.persistence.jdbc.password" value="password" />
      <property name="eclipselink.ddl-generation" value="create-tables" />
      <property name="eclipselink.ddl-generation.output-mode" value="both" />
      <property name="eclipselink.logging.level" value="SEVERE" />
      <property name="eclipselink.logging.file" value="${myDataDir}/derby.log" />
      <property name="eclipselink.application-location" value="${myDataDir}/dbScripts" />
    </properties>
  </persistence-unit>
</persistence>

编辑:

我忘了提一下,我正处于Spring 3 Framework环境中。根据Web上的示例,这应该能够在persistence.xml中使用环境变量...

1 个答案:

答案 0 :(得分:1)

在数据库URL中使用$ {myDataDir}无效,除非您的数据库支持,或者除非您在自己的构建脚本中翻译变量。

您可以做的是将属性映射传递给Persistence.createEntityManagerFactory(),该映射具有您想要的URL,您必须在运行时在代码中构建。

相关问题