You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MapStruct填充同类对象时源空值覆盖目标值如何解决

解决方法

你遇到的配置不生效问题可通过以下步骤逐一排查解决:

  • 确认方法级注解配置正确,示例如下:
@Mapper(componentModel = "cdi")
public interface Mapper {
    @BeanMapping(
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS
    )
    void fill(A source, @MappingTarget A target);
}

NullValuePropertyMappingStrategy.IGNORE的作用恰好是当源属性为null时,保留目标对象的原有属性值,不会覆盖。

  • 如需全局生效,可将配置直接加在@Mapper注解上,无需每个方法重复配置:
@Mapper(
    componentModel = "cdi",
    nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
    nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS
)
public interface Mapper {
    void fill(A source, @MappingTarget A target);
}
  • 检查MapStruct依赖版本:请升级到1.4.2.Final及以上版本,低版本对同类型对象更新场景的策略处理存在兼容bug,会导致配置不生效。

  • 若同时使用Lombok,需要检查项目编译插件的annotationProcessorPaths配置顺序,确保Lombok的处理器配置在MapStruct之前,否则会导致MapStruct无法正常读取类属性,生成错误的映射逻辑。

  • 验证生效状态:编译项目后查看MapStruct自动生成的Mapper实现类,配置生效的前提下,生成的fill方法会包含非空判断逻辑,只有源属性非空时才会赋值给目标对象,最终得到你预期的A(1,2)结果。

内容的提问来源于stack exchange,提问作者Subbies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 00:51:01