Maven - 从外部属性文件中读取属性

zig*_*ggy 17 build release-management maven

我有一个属性文件,包含以下内容

junit.version=3.8.1
dbcp.version=5.5.27
oracle.jdbc.version=10.2.0.2.0
Run Code Online (Sandbox Code Playgroud)

我尝试从我的pom文件中读取这些属性,如下所示

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>${junit.version}</version>
  <scope>test</scope>
</dependency>


<dependency>
    <groupId>dbcp</groupId>
    <artifactId>dbcp</artifactId>
    <version>${dbcp.version}</version>
    <scope>provided</scope>
</dependency>
<dependency>
  <groupId>com.oracle</groupId>
  <artifactId>ojdbc14</artifactId>
  <version>${oracle.jdbc.version}</version>
  <scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

和插件配置

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <executions>
           <!-- Associate the read-project-properties goal with the initialize phase, to read the properties file. -->
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>../live.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
Run Code Online (Sandbox Code Playgroud)

我发现当我运行mvn clean install时它找不到属性,而是出现以下错误:

'dependencies.dependency.version' for junit:junit:jar must be a valid version but is '${junit.version}'. @ line 23, column 16
'dependencies.dependency.version' for dbcp:dbcp:jar must be a valid version but is '${dbcp.version}'. @ line 31, column 12
'dependencies.dependency.version' for com.oracle:ojdbc14:jar must be a valid version but is '${oracle.jdbc.version}'. @ line 37, column 13
Run Code Online (Sandbox Code Playgroud)

上面的失败似乎是在我声明依赖项时我引用属性的情况.我发现在其他一些情况下,从文件中读取属性.例如,如果我在项目版本标签上使用属性(而不是依赖版本),它可以工作

如果从依赖性声明中引用该属性,则该属性似乎不从该文件中读取,但如果从其他任何地方引用,则读取该属性.有任何想法吗?

Eug*_*hov 13

initialize阶段不是清洁生命周期的一部分.您还需要将属性插件绑定到pre-clean阶段.

但是,依赖项解析在解析和执行其他插件之前运行,因此您的方法将无法正常工作.

处理这种情况的正确方法是将依赖版本移动到父pom.xml中,并在两个项目中使用相同的父pom.

  • 对不起,我应该更仔细地阅读你的问题...你不能在<phase>元素中指定多个阶段.但是您不能使用properties-maven-plugin加载的属性来指定依赖项的版本.我用适当的解决方案更新了答案. (3认同)