annotationProcessors 多模块项目 Java

annotationProcessors multi module project Java

我最近开始学习 java 处理器并尝试将它们与 gradle 一起使用, 当我构建项目时,我可以看到打印了注释处理器 jars(其他模块)(我在 app gradle 文件中添加了它,您可以在下面看到),但没有执行。 我不知道我做错了什么...

我有一个具有以下结构的多模块项目

ROOT
|
|-app  # contains main classes
|-annotations
|-processors

处理器项目gradle文件:

plugins {
    id 'java'
}

group 'org.example'
version '1.0-beta'

repositories {
    mavenCentral()
}

dependencies {
    compileOnly project(":annotations")
    implementation(project(":annotations"))
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}

test {
    useJUnitPlatform()
}

应用程序gradle文件

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

tasks.withType(JavaCompile) {
    doFirst {
        println "AnnotationProcessorPath for $name is ${options.getAnnotationProcessorPath().getFiles()}"
    }
}
compileJava {
    options.annotationProcessorPath = configurations.annotationProcessor
}

dependencies {
    compileOnly project(":annotations")
    implementation project(":annotations")
    implementation project(":processors")
    annotationProcessor project(":processors")
//    annotationProcessor  "org.example:processors:1.0-beta"
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}

test {
    useJUnitPlatform()
}

注解一个为默认一个

我有一个记录和创建文件的处理器

@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,"Testa asdfasdf");
 ...

在我的应用程序模块中,我有一个 class 注释模块中声明的 @Builder 注释,因此处理器应该被执行

应用gradle文件的输出

7:59:42 PM: Executing task 'Car.main()'...

> Task :annotations:compileJava UP-TO-DATE
> Task :annotations:processResources NO-SOURCE
> Task :annotations:classes UP-TO-DATE
> Task :annotations:jar UP-TO-DATE
> Task :processors:compileJava UP-TO-DATE
> Task :processors:processResources UP-TO-DATE
> Task :processors:classes UP-TO-DATE
> Task :processors:jar UP-TO-DATE

> Task :app:compileJava
AnnotationProcessorPath for compileJava is [/annotations/processors/build/libs/processors-1.0-beta.jar, /annotations/annotations/build/libs/annotations-1.0-SNAPSHOT.jar]

> Task :app:processResources UP-TO-DATE
> Task :app:classes

> Task :app:Car.main()


BUILD SUCCESSFUL in 242ms
8 actionable tasks: 2 executed, 6 up-to-date
7:59:42 PM: Task execution finished 'Car.main()'.

几个小时后,它通过在处理器模块

下创建文件javax.annotation.processing.Processor来工作
ROOT
|
--app  # contains main classes
--annotations
--processors
  |--main
     |--java
     |--resources
        |--META-INF
           |--services
               |--javax.annotation.processing.Processor
  |--test

将其内容设置为处理器路径,在我的例子中 com.example.processors.BuilderProcessor