How to use custom annotation processor with Maven 2?

nosferat picture nosferat · Jul 26, 2012 · Viewed 7.4k times · Source

In our enterprise application we are seeking a dynamic way to collect data from our Java classes. We created a custom annotation interface (@interface) with a name property. We would like to collect the value of this property from all annotated classes.

I managed to create an AnnotationProcessorFactory and an AnnotationProcessor for the custom annotation. Since we are using Maven 2, I added the following to the plugins in the pom.xml of the main project.

    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>apt-maven-plugin</artifactId>
      <version>1.0-alpha-5</version>
      <configuration>
        <factory>our.company.api.component.lister.ComponentAnnotationProcessFactory</factory>
      </configuration>
    </plugin>

This resides in the main project which has several sub-projects. The factory and the custom processor are in one of these sub-projects. The custom annotations are scattered through all of the sub-projects that is why I put the plugin in the pom.xml of the main project.

The problem is when I issue the mvn apt:process command I got a warning about the annotations without processors and our custom annotation is among them. I assume this means that the plugin cannot find the factory class.

What should I do so the plugin could find the factory and the processor file?

EDIT:

The project hierarchy is very simple:

main_project
|-sub_project1
|...
|-sub_projectn

The plugin is in the pom.xml of the main_project. Just assume that the factory and processor are in sub_project1 and the custom annotations are in sub_project2, sub_project3, ..., sub_projectn

Answer

palacsint picture palacsint · Jul 26, 2012

Two things to check:

  1. Make sure that the main_project (or the plugin) depends on the project which contains your ComponentAnnotationProcessFactory.
  2. The <factory> configuration tag of the Apt Maven Plugin did not work for me but the plugin finds the factory class if its fully qualified name is in the META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory file. (See the documentation of apt for the details.)

A better approach is using the annotation processing features of JDK 6 (instead of the Maven Apt Plugin) since it does not require the com.sun package and the tools.jar from the lib folder of the JDK.

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>

            <configuration>
                <source>1.6</source>
                <target>1.6</target>

                <annotationProcessors>
                    <annotationProcessor>
                        com.example.annotationprocessor.Processor
                    </annotationProcessor>
                </annotationProcessors>
            </configuration>
        </plugin>
    </plugins>
</build>

Further references: