如何将Java注解处理器集成到Java插件中

3

我有一个项目,布局如下:

src/
  java
  generated

src/java包含JPA实体和查询类,这些类使用由Hibernate元模型注释处理器生成的JPA元模型类。

如何将注释处理器合并到Java插件中是最佳方式?

我目前已定义了以下任务,但它依赖于compileJava任务,这将失败,因为某些代码依赖于注释处理器生成的类。

task processAnnotations(type: Compile) {
    genDir = new File("${projectDir}/src/generated")
    genDir.mkdirs()
    source = ['src/java']
    classpath = sourceSets.test.compileClasspath
    destinationDir = genDir
    options.compilerArgs = ["-proc:only"]
}
3个回答

6

以下是一个简单的设置,可以完美地与Netbeans集成。Javac基本上会在不需要太多干预的情况下完成所有需要的工作。其余的小调整将使其与诸如Netbeans之类的IDE一起使用。

apply plugin:'java'

dependencies {
    // Compile-time dependencies should contain annotation processors
    compile(group: 'org.hibernate...', name: '...', version: '...')
}

ext {
    generatedSourcesDir = file("${buildDir}/generated-sources/javac/main/java")
}

// This section is the key to IDE integration.
// IDE will look for source files in both in both
//
//  * src/main/java
//  * build/generated-sources/javac/main/java
//
sourceSets {
    main {
        java {
            srcDir 'src/main/java'
            srcDir generatedSourcesDir
        }
    }
}

// These are the only modifications to build process that are required.
compileJava {
    doFirst {
        // Directory should exists before compilation started.
        generatedSourcesDir.mkdirs()
    }
    options.compilerArgs += ['-s', generatedSourcesDir]
}

就是这样,Javac会完成剩下的工作。


3
processAnnotations 依赖于 compileJava 的原因是你把测试编译类路径放在前者任务的编译类路径上,而测试编译类路径包含编译生产代码的输出(即compileJava的输出)。
至于如何最好地解决手头的问题,你不需要一个单独的编译任务。Java编译器可以调用注解处理器并在一次编译中编译它们生成的源码(以及原始源码)(请参见 Annotation Processing)。你需要做的一件事是将注解处理器放在编译类路径上:
configurations {
    hibernateAnnotationProcessor
}

dependencies {
    hibernateAnnotationProcessor "org.hibernate: ..."
}

compileJava.compileClasspath += configurations.hibernateAnnotationProcessor

(如果您将注释处理器添加到compile配置中,那么它将被视为生产代码的依赖项。)据我所知,这就是全部内容(假设您使用JDK6或更高版本)。

我走了单任务的路线,但编译时出现了无效标志-s错误。所以我将其作为一个单独的任务保留了下来。但你提供的信息帮了很大的忙。谢谢。 - Craig Swing
这对我部分起作用。我还需要告诉编译器关于我的处理器的信息,类似于这样:compileJava.options.compilerArgs = ["-processor", "完全限定的处理器路径.MyProcessor"] - Ryan Walls

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接