如何使用Maven从模板生成源代码?

时间:2013-05-10 07:05:46

标签: java maven code-generation

我有一个包含令牌列表的文件:

tokens.txt

foo
bar
baz

和模板文件:

template.txt

public class @token@MyInterface 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 个答案:

答案 0 :(得分: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>