2017-07-03 104 views
1

我試圖使用properties-maven-plugin在構建時讀取項目屬性,然後使用maven-resources-plugin替換文本文件中的屬性。以下是他們的宣言:動態Maven項目屬性在資源中未被替換

<plugin> 
    <groupId>org.codehaus.mojo</groupId> 
    <artifactId>properties-maven-plugin</artifactId> 
    <version>1.0-alpha-1</version> 
    <executions> 
     <execution> 
     <phase>initialize</phase> 
     <goals> 
      <goal>read-project-properties</goal> 
     </goals> 
     <configuration> 
      <files> 
      <file>${basedir}/src/main/resources/sample.properties</file> 
      </files> 
     </configuration> 
     </execution> 
    </executions> 
    </plugin> 

<plugin> 
    <artifactId>maven-resources-plugin</artifactId> 
    <version>2.7</version> 
    <executions> 
     <execution> 
     <id>copy-resources</id> 
     <phase>package</phase> 
     <goals> 
      <goal>copy-resources</goal> 
     </goals> 
     <configuration> 
      <overwrite>true</overwrite> 
      <outputDirectory>${basedir}/target</outputDirectory> 
      <resources> 
      <resource> 
       <directory>${basedir}/src/main/resources</directory> 
       <includes> 
       <include>**/*.txt</include> 
       </includes> 
       <filtering>true</filtering> 
      </resource> 
      </resources> 
     </configuration> 
     </execution> 
    </executions> 
    </plugin> 

下面是sample.propertieshello.txt目前該內容的src/main/resources

sample.properties 
name=test_user 

hello.txt 
Hello ${name} 

在目標目錄中創建作爲構建過程的結果沒有預期的內容的src/main/resources/hello.txt

Expected hello.txt 
Hello test_user 

Actual hello.txt 
Hello ${name} 

有人可以請解釋我做錯了什麼嗎?

PS:我添加了ant任務來打印項目屬性$ {name}來檢查properties-maven-plugin的功能,它似乎工作正常。

:如果其他人也面臨同樣的問題,然後嘗試在你的IDE(Eclipse在我的情況)這OUT-

關閉自動構建,然後生成項目。什麼可能是錯誤的,你的IDE繼續構建項目(替換資源中的屬性)比運行時項目屬性由properties-maven-plugin設置更早。它爲我工作。

+0

請在github上做一個完整的工作示例,以便我可以看看... – khmarbaise

回答

0

要過濾資源的慣例是通過保持要過濾的文件src/main/resources做過濾:

<project> 
    ... 
    <build> 
    ... 
    <resources> 
     <resource> 
     <directory>src/main/resources</directory> 
     <filtering>true</filtering> 
     </resource> 
     ... 
    </resources> 
    ... 
    </build> 
    ... 
</project> 

如果你喜歡包含/排除您可以使用文件包含/排除部分這樣的:

<build> 
    ... 
    <resources> 
     <resource> 
     <directory>src/my-resources</directory> 
     <includes> 
      <include>**/*.txt</include> 
      <include>**/*.rtf</include> 
     </includes> 
     </resource> 
     ... 
    </resources> 
    ... 
    </build> 

沒有必要使用屬性 - Maven的插件讀取性能和明確的行家 - 資源 - 插件添加到生命週期的原因是有默認。

+0

我按照您的建議刪除了maven-resources-plugin聲明。現在要被替換的資源在構建元素中指定。它仍然不起作用。另外,我的用例涉及到properties-maven-plugin。你能提出其他的選擇嗎? – user2653926