首页 > 解决方案 > 自定义注释处理器未运行

问题描述

出于测试原因,我编写了一个 AnnotationProcessor,它不是由 maven 执行的。

我正在使用谷歌的“自动服务”为我创建 META-INF 数据。

这是处理器:

@SupportedAnnotationTypes({ "test.TestAnnotation" })
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@AutoService(Processor.class)
public class AnnotationProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        System.out.println("Test");
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Test");
        return true;
    }

}

我还尝试抛出异常、创建文件、使用断点运行 mvnDebug 等。对我来说没有任何效果。

这是项目中提供处理器的重要部分(剩下的只是groupId、命名等):

<dependencies>
    <dependency>
        <groupId>com.google.auto.service</groupId>
        <artifactId>auto-service</artifactId>
        <version>1.0-rc4</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <compilerArgument>-proc:none</compilerArgument>
            </configuration>
        </plugin>
    </plugins>
</build>

这是项目 POM 的重要部分,它使用注释进行代码生成:

<dependencies>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>Annotation</artifactId>
        <version>${project.version}</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
        </plugin>
    </plugins>
</build>

我的最终目标是让项目将我的注释处理器添加为依赖项并准备好使用(有点像龙目岛)。

编辑 测试注释正在测试类上使用。

标签: javamavenannotationsannotation-processing

解决方案


以下 pom 有效。Maven在这里非常严格。没有带有 Path 或 annotationProcessorPath 的 annotationProcessorPaths,没有带有 annotationProcessor 的 annotationProcessor (据我所知,这些都是准备好的罐子。

              <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                    <configuration> 
                        <source>10</source>
                        <target>10</target>
                        <outputDirectory>${generatedSources}</outputDirectory>
                        <annotationProcessorPath>
                              <artifactId>processing</artifactId>
                              <name>annotation_processing</name>    
                              <version>0.0.1-SNAPSHOT</version>                 
                        </annotationProcessorPath>
                    </configuration>
              </plugin>

Maven 编译安装成功。


推荐阅读