【问题标题】:MapStruct with groovy classes带有 groovy 类的 MapStruct
【发布时间】:2021-11-21 08:30:10
【问题描述】:

我想在带有 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
}

问题是没有生成映射器的实现类。 我还尝试为 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"))
}

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

【问题讨论】:

  • 为什么在 Groovy 中需要 MapStruct?你的用例是什么?
  • 不同对象之间的映射,能够在 MapStruct 注释中指定一些特定的映射规则。一个例子可以是类中不同的属性名称,或者有时我必须忽略空属性

标签: groovy mapstruct


【解决方案1】:

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

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

有了这个Car(从他们的例子稍微修改了)

import groovy.transform.Immutable

@Immutable
class Car {
    String make;
    int numberOfSeats;
    CarType type;
}

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

import groovy.transform.ToString

@ToString
class CarDto {

    String make;
    int seatCount;
    String type;
}

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

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)
}

然后你可以这样做:

class Main {

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

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

        println carDto
    }
}

打印出来的:

main.CarDto(Morris, 5, SEDAN)

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多