Stephan
Stephan

Reputation: 43053

How to generate source code from template with Maven?

I have a file with a list of tokens:

tokens.txt

foo
bar
baz

and a template file:

template.txt

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

I want to generate the following source code files to target/generated-sources/my/package:

One of the generated source files look like this:

FooMyInterface.java

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

How can I do this with Maven ?

Upvotes: 5

Views: 4546

Answers (1)

Daniel Kaplan
Daniel Kaplan

Reputation: 67440

What you're looking to do is called filtering. You can read more about it here. As you can see, you'll have to change the way you're doing some things. The variables are defined differently. You'll want to rename the file to a .java.

But then you've got another problem: This will take a source file and replace the variables with literals, but it wont compile the .java file for you when you build your project. Assuming you want to do that, here's a tutorial on how. I'm going to inline some of that tutorial just in case it disappears some day:

Example source file:

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

The filtering:

<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>

Now change the directory in which maven finds the source files to compile:

<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>

Upvotes: 1

Related Questions