【问题标题】:MapStruct Custom EnumTransformationStrategyMapStruct 自定义 EnumTransformationStrategy
【发布时间】:2021-10-27 00:03:06
【问题描述】:

看到documentation 关于如何对枚举使用自定义转换策略,我有点困惑。我在 Kotlin 中执行此操作,但 Java 解决方案也可以。

我使用的是 14.2

我有这个

package org.mapstruct.custom.spi
import org.mapstruct.ap.spi.EnumTransformationStrategy

class StripLowerCaseEnumTransformationStrategy : EnumTransformationStrategy {
    companion object {
        const val NAME = "stripLowerCase"
    }

    override fun getStrategyName(): String {
        return NAME
    }

    override fun transform(value: String, configuration: String): String {
        return value.removePrefix(configuration).toLowerCase()
    }
}

但是当我尝试在我的 EnumMappers 中使用它时,它说找不到它。我错过了哪一步?

@Mapper
interface EnumMapper {
  @ValueMappings(
        ValueMapping(source = "UNRECOGNIZED", target = MappingConstants.NULL),
        ValueMapping(source = "PERSON_STATUS_INVALID", target = MappingConstants.NULL)
    )
  @EnumMapping(
        nameTransformationStrategy = StripLowerCaseEnumTransformationStrategy.NAME,
        configuration = "PERSON_STATUS_"
    )
  fun fromProto(status: PersonStatusProto): PersonStatus

  @InheritInverseConfiguration
  fun toProto(status: PersonStatus): PersonStatusProto
}

这是错误:error: There is no registered EnumTransformationStrategy for 'stripLowerCase'. Registered strategies are: prefix, stripPrefix, stripSuffix, suffix.

我还创建了文件resources/META-INF/services/org.mapstruct.ap.spi.EnumTransformationStrategy,其值为org.mapstruct.custom.spi.StripLowerCaseEnumTransformationStrategy

这里还有一张目录图片,以防它组织不正确:

【问题讨论】:

    标签: java kotlin mapstruct


    【解决方案1】:

    之所以没有使用配置的EnumTransformationStrategy是因为没有使用仅在同一个编译单元中可用的SPI。

    为了使其工作,您需要将实现移动到不同的模块(而不是包)中并在编译期间使其可用l

    可以在this 集成测试中看到如何使用 maven 完成此操作的示例。

    注意:我看到您将StripLowerCaseEnumTransformationStrategy 放在org.mapstruct 包下。我建议不要使用你不拥有的包来放置你的代码,否则在 Java 模块路径上运行时你可能会遇到拆分包的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 2018-04-13
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多