How to create source code from a template with Maven?

I have a file with a list of tokens:

tokens.txt

foo bar baz 

and 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 in target/generated-sources/my/package :

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

One of the generated source files looks 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?

+4
source share
1 answer

What you want to do is called filtering. You can read about it here. As you can see, you will have to change the way you perform certain actions. Variables are defined differently. You will want to rename the file to .java.

But then you have one more problem: it will take the source file and replace the variables with literals, but it will not compile the .java file for you when creating your project. Assuming you want to do this, here's a tutorial on how. I am going to include part of this tutorial in case it disappears once:

An example of the source file:

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

Filtration:

 <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 where 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> 
+1
source

Source: https://habr.com/ru/post/1480054/


All Articles