2013-05-10 52 views
4

我有標記列表的文件:如何使用Maven從模板生成源代碼?

tokens.txt

foo 
bar 
baz 

和模板文件:

template.txt

public class @[email protected] implements MyInterface { 
    public void doStuff() { 
     // First line of generated code 
     // Second line of generated code 
    } 
} 

我想要生成以下源代碼文件到target/generated-sources/my/package

  • FooMyInterface.java
  • BarMyInterface.java
  • BazMyInterface.java

一個生成的源文件是這樣的:

FooMyInterface.java

public class FooMyInterface implements MyInterface { 
    public void doStuff() { 
     // First line of generated code 
     // Second line of generated code 
    } 
} 

我如何用Maven做到這一點?

回答

1

你要做的就是過濾。 You can read more about it here.正如你所看到的,你必須改變你做某些事情的方式。變量的定義不同。您需要將該文件重命名爲.java。

但是接下來你會遇到另外一個問題:這將需要一個源文件並用文字替換變量,但是當你生成你的項目時,它不會爲你編譯.java文件。假設你想這樣做,here's a tutorial on how.我要內嵌一些教程以防萬一它消失的某一天:

示例源文件:

public static final String DOMAIN = "${pom.groupId}"; 
public static final String WCB_ID = "${pom.artifactId}"; 

過濾:

<project...> 
    ... 
    <build> 
    ... 
    <!-- Configure the source files as resources to be filtered 
     into a custom target directory --> 
    <resources> 
     <resource> 
     <directory>src/main/java</directory> 
     <filtering>true</filtering> 
     <targetPath>../filtered-sources/java</targetPath> 
     </resource> 
     <resource> 
     <directory>src/main/resources</directory> 
     <filtering>true</filtering> 
     </resource> 
    </resources> 
    ... 
    </build> 
... 
</project> 

現在更改maven找到要編譯的源文件的目錄:

<project...> 
    ... 
    <build> 
    ... 
     <!-- Overrule the default pom source directory to match 
      our generated sources so the compiler will pick them up --> 
     <sourceDirectory>target/filtered-sources/java</sourceDirectory> 
    ... 
    </build> 
... 
</project> 
+0

這是屬性嗎?只有一個文件? – Stephan 2013-05-10 07:39:56

+0

是的,當我寫這個時,我忘記了這個要求。要做到這一點,它看起來像這樣的答案將有所幫助:http://stackoverflow.com/questions/3308368/maven-how-to-filter-the-same-resource-multiple-times-with-different-property- VA – 2013-05-10 07:44:36

相關問題