简体   繁体   中英

Integrating annotation processors with Gradle

I need to write some annotation processors. I found this blog post which mentions how that can be done in a general setting and with Eclipse.

However I am using IntelliJ IDEA and Gradle, and woud like it if there were a better (as in, less tedious) approach to do it. What I am looking for:

  1. I should be able to write both annotation processors and the code that will be consuming them in the same project and Gradle should handle adding the processors to class path and invoking them with javac at approrpiate stage.
    OR
  2. If the above is not possible and I have to create two separate projects, then at least it should be possible to keep them in the same git repository. Gradle should handle the build seamlessly.
    OR
  3. If neither is possible and I have to create two separate git repositories, then at the very least, Gradle should handle the things mentioned in the linked blog post seamlessly without further manual intervention.

My git and Gradle skills are beginner level. I would appreciate any help with this task. Thank you.

Yes, it is possible to move processor to separated module and use it from another module (see querydslapt below).

I will recomend you to implement your own AbstractProcessor

and use it like that:

dependencies {
    ....
    // put dependency to your module with processor inside
    querydslapt "com.mysema.querydsl:querydsl-apt:$querydslVersion" 
}

task generateQueryDSL(type: JavaCompile, group: 'build', description: 'Generates the QueryDSL query types') {
    source = sourceSets.main.java // input source set
    classpath = configurations.compile + configurations.querydslapt // add processor module to classpath
    // specify javac arguments
    options.compilerArgs = [
            "-proc:only",
            "-processor", "com.mysema.query.apt.jpa.JPAAnnotationProcessor" // your processor here
    ]
    // specify output of generated code
    destinationDir = sourceSets.generated.java.srcDirs.iterator().next()
}

You can find the full example here

Another solution (in my opinion cleaner) could be to have two subprojects and then simply make the one that contains annotation processors a dependency of the main one. So given two directories with your subprojects: core and annotation-processors in the root of your project, you would need to also have a settings.gradle file with the following:

include 'core'
include 'annotation-processors'

And then in the gradle file for the core project:

dependencies {
    compile project(':annotation-processors')
}

That should do it and you won't have to deal with custom compile tasks and their classpaths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM