我想在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类协同工作,以及我如何配置它?
发布于 2021-09-29 16:14:06
因此,您可以使用此构建:
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)https://stackoverflow.com/questions/69376275
复制相似问题