具有常规类的 MapStruct

Tob*_*aft 0 groovy mapstruct

我想在带有 gradle 的 groovy 类上使用 Mapstruct 映射器。build.gradle 中的配置看起来像 Java 项目中的配置。

dependencies {
    ...
    compile 'org.mapstruct:mapstruct:1.4.2.Final'

    annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
    testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final' // if you are using mapstruct in test code
}
Run Code Online (Sandbox Code Playgroud)

问题是没有生成映射器的实现类。我还尝试为 groovy 编译任务应用不同的选项,但它不起作用。

compileGroovy {
    options.annotationProcessorPath = configurations.annotationProcessor
    // if you need to configure mapstruct component model
    options.compilerArgs << "-Amapstruct.defaultComponentModel=default"
    options.setAnnotationProcessorGeneratedSourcesDirectory( file("$projectDir/src/main/generated/groovy"))
}
Run Code Online (Sandbox Code Playgroud)

有谁知道 Mapstruct 是否可以与 groovy 类一起工作以及我必须如何配置它?

tim*_*tes 5

所以你可以使用这个构建:

plugins {
    id 'groovy'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.mapstruct:mapstruct:1.4.2.Final'
    implementation 'org.codehaus.groovy:groovy-all:3.0.9'
    annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
}

compileGroovy.groovyOptions.javaAnnotationProcessing = true
Run Code Online (Sandbox Code Playgroud)

这样Car(对他们的示例稍作修改)

import groovy.transform.Immutable

@Immutable
class Car {
    String make;
    int numberOfSeats;
    CarType type;
}
Run Code Online (Sandbox Code Playgroud)

还有这个CarDto(再次稍作修改)

import groovy.transform.ToString

@ToString
class CarDto {

    String make;
    int seatCount;
    String type;
}
Run Code Online (Sandbox Code Playgroud)

那么您需要在 中进行的唯一更改CarMapper就是忽略metaClassGroovy 添加到对象的属性:

import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.factory.Mappers

@Mapper
interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper)

    @Mapping(source = "numberOfSeats", target = "seatCount")
    @Mapping(target = "metaClass", ignore = true)
    CarDto carToCarDto(Car car)
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

class Main {

    static main(args) {
        Car car = new Car("Morris", 5, CarType.SEDAN);

        CarDto carDto = CarMapper.INSTANCE.carToCarDto(car);

        println carDto
    }
}
Run Code Online (Sandbox Code Playgroud)

打印出:

main.CarDto(Morris, 5, SEDAN)
Run Code Online (Sandbox Code Playgroud)