Home > Mobile >  QueryDSL with Gradle configuration of annotation processor
QueryDSL with Gradle configuration of annotation processor

Time:11-16

I searched a lot regarding the configuration of QueryDSL with Gradle. I would like to configure the annotation processor, to use a specific annotation @Generated on the generated classes.

This is my build.gradle (resumed):

plugins {
    id 'java'
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.6'
    annotationProcessor 'org.springframework.boot:spring-boot-starter-data-jpa:2.5.6'
    implementation 'com.querydsl:querydsl-jpa:5.0.0'
    annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jpa"
}

compileJava {
    finalizedBy 'generateQueryDSL'
}

task generateQueryDSL(type: JavaCompile) {
    source = sourceSets.main.java.srcDirs
    classpath = sourceSets.main.compileClasspath
    getDestinationDirectory().set(file("$buildDir/generated/sources/annotationProcessor/java/main"))
    options.annotationProcessorPath = configurations.annotationProcessor
    options.compilerArgs = [
        '-proc:only',
        '-processor',
        'com.querydsl.apt.jpa.JPAAnnotationProcessor',
        '-Aquerydsl.generatedAnnotationClass=com.querydsl.core.annotations.Generated'
    ]
}

Is there an easier way to configure the annotation processor? I had a LOT of troubles with this approach, because the original method keeps changing the file with the OLD annotation, because I can't replace this old behavior. And with this, there are tasks (or steps inside the "compileJava" task) that I can't remove or override.

CodePudding user response:

If all you want to do is configure the QueryDSL processor, without specifically splitting annotation processing from compilation, then all you have to do is to pass the -Aquerydsl.generatedAnnotationClass=… compiler argument to the compileJava class. No need for a separate task.

compileJava {
    options.compilerArgs << '-Aquerydsl.generatedAnnotationClass=com.querydsl.core.annotations.Generated'
}

The issues with the setup in your question:

  • -proc:only disables compilation, to only process annotations and generate code (in options.generatedSourceOutputDirectory)
  • -processor listing only the QueryDSL processor will disable all other annotation processors in the processor path
  • that task was configured as finalizedBy of the compileJava, so compileJava would compile your code, applying all annotation processors, without the specific configuration you want to pass to the QueryDSL processor, and only then re-run the QueryDSL processor with a specific option but without compiling, so it would generate source code (e.g. for use in your IDE) with the proper configuration, but won't compile it, so the compiled classes would still have the "wrong" configuration from the unconfigured compileJava task
  • Related