Maven example of annotation preprocessing and generation of classes in same compile process?
Does anyone have a clean example of a maven project preprocessing class annotations at compile time with subsequent generation of classes to be compiled in the same compilation process?
Does anyone have a step-by-step procedure to impl开发者_Python百科ement such a project?
After navigating a lot in existing documentation on the net, I came up with the following:
What needs to be clarified:
- In order to process annotations on a given project P, you first need an annotation processor compiled in a separate library S. P should have a dependency on S.
- Implementing annotation processing in Java 5 is absolutely not the same thing as in Java 6.
- Java 5 relies on a separate execution of apt. The corresponding tutorials here and here help understanding the basics of annotation processing and implementation in Java 5. Good reading for newbies.
- Implementing annotation processing in Java 5 with Maven is tricky. One needs to add a local dependency to
tools.jar
to access the API described in these tutorials. Not clean. Some third-party plugins calling the apt are available, but not well documented. - Those using Java 6 should not jump-start implementing their processors according to the above tutorials.
Annotation Processing in Java 6 with Maven
- A new package has been delivered in Java 6 to process annotations: the Pluggable Annotation Processing.
- To implement a processor, create a separate Maven project. The above tutorial or this one explains how to proceed. This is our library S.
- Then, create your project P and add a Maven dependency on S.
- There is currently an issue with the maven-compiler-plugin, but a workaround is available here. Use it to compile your generated code as part of existing annotated code.
...and code generation
- A great Java code generation library called CodeModel is available from Maven central. A good tutorial is available here. The javax annotation processing package offers some tools to generate output too.
maven-processor-plugin can do that...
https://code.google.com/p/maven-annotation-plugin/
Example from documentation:
<build> <plugins>
<!-- Run annotation processors on src/main/java sources -->
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
</execution>
</executions>
</plugin>
<!-- Disable annotation processors during normal compilation -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
</plugins> </build>
The Maven-Antlr-Plugin exactly does this. It generates Java classes from a grammar and the compile plugin compiles the generated classes. May it might be usefull the maven-annotation-plugin
精彩评论