Как успешно интегрировать Gradle, MapStruct 1.3.1 и Eclipse 2020-03? - PullRequest
0 голосов
/ 02 апреля 2020

Есть ли документация или пример, в котором излагается, как успешно интегрировать MapStruct 1.3.1 с Eclipse 2020-03 и Gradle / Buildship, и в котором описывается, что необходимо сделать для создания классов реализации MapStruct? Я проделал немалую часть поиска и чтения, но, похоже, не могу прижиться к нему, попробовав немало вещей.

Мой проект настроен на многопроектную настройку Gradle, и она работала нормально. пока я не попытался добавить MapStruct через Gradle. У меня есть JAX-RS REST классы с аннотациями в моем проекте, и проблемы, которые я вижу, как-то связаны с обработкой аннотаций, поскольку сборка завершается с ошибками компиляции для аннотаций в классах REST (см. Вывод исключений ниже).

Любые указатели, дальнейшее чтение, исправления приветствуются и приветствуются.

Исключение, которое я получаю, когда запускаю соответствующую задачу build в представлении Eclipse Gradle Tasks:

D:\<placeholder>\PlanContractualDetails.java:527: error: cannot find symbol
  @ApiModelProperty(example = "null", required = true, value = "True - life time investment option phasing applicable. Please note that this value will be always populated by using the active LTIO on the plan, irrespective of the effectiveDate passed by the caller.")
   ^
  symbol:   class ApiModelProperty
  location: class PlanContractualDetails
100 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':epsilon-plan-service:compileJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.3/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 563ms
1 actionable task: 1 executed

Мой build.gradle выглядит следующим образом:

/*
 * Project build file.
 */

 /* Plugin configuration */
plugins {
    id 'java'
    id 'war'
    id 'eclipse-wtp'
}

sourceCompatibility = JavaVersion.VERSION_1_8
/* Project dependencies */
dependencies { 

    compile "org.mapstruct:mapstruct-jdk8:${mapstructVersion}"
    testCompile 'org.testng:testng:6.10', 'org.easytesting:fest-assert:1.4'
    compile "org.mapstruct:mapstruct-processor:${mapstructVersion}"

    compile "javax.ws.rs:javax.ws.rs-api:2.0.1"
    providedCompile "javax.servlet:javax.servlet-api:3.1.0" 

    // --- Mapstruct ---------------------------------
    // https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8
     //compile group: 'org.mapstruct', name: 'mapstruct-jdk8', version: '1.3.1.Final'
    // https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor
    //compile group: 'org.mapstruct', name: 'mapstruct-processor', version: '1.3.1.Final'
    //compile "org.mapstruct:mapstruct:${mapstructVersion}"

    // If you are using mapstruct in test code
    //testAnnotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
    //compileOnly("org.mapstruct:mapstruct-jdk8:${mapstructVersion}")
    //annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"

    //compileOnly "javax:javaee-api:${javaee_api_version}"
}

tasks.withType(JavaCompile) {
    options.compilerArgs = [
            '-Amapstruct.suppressGeneratorTimestamp=true'
    ]
}

sourceSets.main.java.srcDirs += 'src'
//sourceSets.main.kotlin.srcDirs += myDir

/* Eclipse configuration */
ext.outputDir = 'src/main/webapp/WEB-INF/classes'
eclipse {
/*
    project {
        natures 'org.eclipse.buildship.core.gradleprojectnature'

        //buildCommands.clear();
        //buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
    }
*/
    classpath {
        defaultOutputDir = file("${outputDir}")
        file.whenMerged {
            entries.each {
                source ->
                    // This seems kludgy.
                    if (source.kind == 'src' && source.toString().contains('output=') && source.output.contains("${eclipse_default_output_dir}")) {
                        source.output = "${outputDir}"
                    }
            }
        }
    }

    /* 

        Deal with project facets.
        See: https://stackoverflow.com/questions/48828869/how-to-convert-java-gradle-project-to-dynamic-web-project
        And: https://discuss.gradle.org/t/easily-customize-the-eclipse-wtp-facet-version/8690
        And: https://github.com/gradle/gradle/issues/1334
    */
  wtp {
    facet {
      file {
        withXml {
            /* 
                Ensure that the Eclipse facet metadata in the file .settings/org.eclipse.wst.common.project.facet.core.xml
                is preserved after running this build script. This is needed as Gradle overwrites this file and defaults 
                some of the entries to older versions which may result in both Eclipse metadata and Gradle build errors.                    
            */
            def node = it.asNode()
            /*
                This runtime facet is specifically for Eclipse projects such as a Dynamic Web Project project created 
                for development, deployment and debugging on WebSphere Application Server traditional V9.0.

                The name: must correspond to the name Properties -> Project Facets -> Runtimes tab entry 
                that is ticked for this Eclipse project.
            */
                node.appendNode('runtime', [name: 'WebSphere Application Server traditional V9.0'])
            }
            def oldJstWebFacet = facets.findAll {
                it.name == 'jst.web' && it.version == '2.4'
            }
            facets.removeAll(oldJstWebFacet)
            facet name: 'jst.web', version: '3.1'

            /*
                Additional Eclipse project facets for WebSphere 9 traditional.
            */
            facet name: 'com.ibm.websphere.coexistence.web', version: '9.0'
            facet name: 'com.ibm.websphere.extended.web', version: '9.0'

            //facet name: 'java', version: '1.8'         
      }
    }
  }
}

test {
    useTestNG()
}```


1 Ответ

1 голос
/ 05 апреля 2020

Моя проблема оказалась не проблемой MapStruct и не была связана с обработкой аннотаций. Я сделал все заново с нуля, но перед генерацией любого кода JAX-RS или MapStruct протестировал конфигурацию MapStruct Gradle, и она прошла. Затем добавил пример кода MapStruct, и он все еще был счастлив; Добавление привязок JAX-RS привело к сбою сборки. Исправление состояло в том, чтобы добавить правильные зависимости JAX-RS и перестроить метаданные Eclipse, выполнив очистку и сборку Eclipse.

...