Kotlin中使用MapStruct映射OpenApi生成的数据类报错咨询
在Kotlin项目中使用MapStruct处理OpenApi生成的数据类
问题分析
你遇到的编译错误提示Property "attributes" has no write accessor in PaymentMethodResponse,但你提供的PaymentMethodResponse只包含id字段,核心原因是:
- 实际OpenApi生成的
PaymentMethodResponse类中存在attributes字段(你未完整粘贴代码); - MapStruct解析类结构时识别到了该字段,但无法找到对应的写入方式(构造器参数、setter方法)。
解决方案
1. 处理attributes字段
根据业务需求选择以下方式:
- 忽略冗余字段:如果
attributes是不需要的生成冗余字段,直接在映射器中显式忽略:
@Mapper(injectionStrategy = InjectionStrategy.CONSTRUCTOR) interface PaymentMethodMapper { @Mapping(source = "paymentMethodId", target = "id") @Mapping(target = "attributes", ignore = true) // 跳过该字段的映射 fun mapToDto(paymentMethod: PaymentMethod): PaymentMethodResponse }
- 修复字段注解:如果
attributes是有效业务字段,检查其注解方式。OpenApi默认生成的@get:JsonProperty仅标注在getter上,会导致MapStruct无法关联到构造器参数。调整OpenApi Generator配置,让注解生成在字段上(以Gradle插件为例):
openApiGenerate { generatorName = "kotlin" configOptions = [ "annotationLibrary": "jackson", "useFieldAccessors": "true", "JsonPropertyAnnotationUseField": "true" // 让@JsonProperty标注在字段上 ] }
调整后生成的数据类示例:
data class PaymentMethodResponse( @field:JsonProperty("id") val id: java.util.UUID? = null, @field:JsonProperty("attributes") val attributes: Any? = null )
此时MapStruct可通过Kotlin data class的全参构造器正确识别字段写入方式。
2. 确保MapStruct与Kotlin兼容
- 使用支持Kotlin的MapStruct版本(推荐1.5.5.Final及以上),在
build.gradle.kts中配置:
dependencies { implementation("org.mapstruct:mapstruct:1.5.5.Final") kapt("org.mapstruct:mapstruct-processor:1.5.5.Final") } kapt { arguments { arg("mapstruct.injectionStrategy", "CONSTRUCTOR") arg("mapstruct.defaultComponentModel", "spring") // 按需选择组件模型 } }
3. 检查源类字段
确认PaymentMethod类中不存在attributes字段,避免MapStruct自动尝试映射未配置的字段。如果存在且无需映射,同样添加@Mapping(target = "attributes", ignore = true)。
内容的提问来源于stack exchange,提问作者user1488550
相关产品推荐
相关产品推荐

