[英]How to configure MapStruct to throw an exception when enum values can't be mapped
这是我的映射器:
@Mapper
public interface ProductMapper {
ProductClassification toProductClassification(ProductTypes pisType);
}
其中ProductTypes
和ProductClassification
是枚举。 我希望它在无法 map 枚举时抛出异常,但我得到编译器错误: The following constants from the source enum have no corresponding constant in the target enum and must be be mapped via adding additional mappings: EXTERNAL, UNKNOWN.
我尝试使用@ValueMappings
注释,但只能将其配置为将值设置为null,这还不够:
@ValueMappings({
@ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL)
})
当 MapStruct 映射器不能 map 枚举常量时,配置 MapStruct 映射器以引发异常的正确方法是什么?
目前这是不可能的。
但是,此功能将成为下一个 1.5 版本的一部分。 它已经在 SNAPSHOT 构建中实现并可用。
将有一个可以通过MappingConstants.THROW_EXCEPTION
访问的新映射常量,您可以将其设置为ValueMappingTarget
。
因此,在此示例中,为了对任何剩余的映射抛出异常,您可以编写:
@ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.THROW_EXCEPTION)
请注意,在回答此问题时 (29.03.2021),此功能尚未发布。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.