Mapstruct AnnotationProcessor with IntelliJ and Gradle

给你一囗甜甜゛ 提交于 2021-01-29 20:15:56

问题


I am trying to get the Mapstruct annotation processor to work in IntelliJ in a Gradle project.

Ideally, I would expect for all configuration to be in the gradle-file and that anyone could just import the project into IntelliJ and get a complete setup without having to set any preferences manually.

But I am okay with compromises on that.

I am using IntelliJ 2018.3 and Gradle 5.0 with Java 11 (i.e. the latest and greatest). The Mapstruct version is 1.2.0.FINAL.

What I have done:

  • Configured the Mapstruct annotation processor in my build.gradle:

    compile "org.mapstruct:mapstruct-jdk8:${mapstruct_version}"
    annotationProcessor "org.mapstruct:mapstruct-processor:${mapstruct_version}"
    
  • Selected "Delegate IDE build/run actions to Gradle" in the Preferences under "Build, Execution, Deployment -> Build Tools -> Gradle -> Runner"

In the directory build/classes/java/main/com/myapp/mypackage/mapper/ I see a MyMapperImpl.class and a MyMapperImpl.java, so code generation seems to work.

Now I would expect that when I select my annotated abstract MyMapper class and press ctrlH, that the generated MyMapperImpl appears in the hierarchy view.

If I manually mark build/classes/java/main/ as a "generated sources" directory (which I really don't want to have to do, see above), the class still does not appear in the hierarchy. But the source code is marked with a lot of errors, as no classes from my project are found, apparently.

Needless to say: I can flawlessly run tests that use the mapper, both from IntelliJ and the command line.


回答1:


Use this, my team is also using mapstruct and we use it in our build.gradle, you will need to bring the idea plugin for gradle as well

def generatedSources = "$buildDir/generated"
def generatedOutputDir = file("$generatedSources")

/*
 create generated .java files in different folder than classes
 In IntelliJ 2016.3.x: Enable Annotation Processing, then set generated sources,
 relative to module output dir, at path '../../generated'
 */
compileJava {
    doFirst {
        generatedOutputDir.exists() || generatedOutputDir.mkdirs()
        options.compilerArgs = [
                '-s', "${generatedSources}"
        ]
    }
}


idea {
    module {
        downloadSources = true
        // tell intellij where to find generated sources
        sourceDirs += generatedOutputDir
    }
}

You will able to run your code even without Gradle runner with this workaround



来源:https://stackoverflow.com/questions/53816022/mapstruct-annotationprocessor-with-intellij-and-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!