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

MapStruct中源List为null时如何设置默认空列表[]?

MapStruct处理集合属性null时返回空列表的正确方式

你遇到的问题是误用了defaultValue属性——这个属性仅支持字符串常量值,无法直接解析Java表达式,所以编译器会尝试把"java(List.of())"这个字符串转换为List类型,自然报错。

以下是两种正确实现方式:

方式一:使用expression属性自定义逻辑

通过expression属性编写Java判断逻辑,直接处理null场景:

// 需要先在Mapper接口上导入List类
@Mapper(imports = java.util.List.class)
public interface YourMapper {
    @Mapping(source = "deptList", target = "deptList", 
             expression = "java(source.getDeptList() != null ? source.getDeptList() : List.of())")
    TargetEntity toTarget(SourceEntity source);
}

注意:List.of()返回的是不可变列表,如果目标实体的deptList是可变集合(如ArrayList),建议改用new java.util.ArrayList<>()替代。

方式二:使用MapStruct内置的空值映射策略(更优雅)

MapStruct提供了NullValuePropertyMappingStrategy,可以一键配置null属性的默认值:

局部方法配置

仅针对当前属性生效:

public interface YourMapper {
    @Mapping(source = "deptList", target = "deptList", 
             nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT)
    TargetEntity toTarget(SourceEntity source);
}

全局Mapper配置

对整个Mapper接口的所有属性生效:

@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT)
public interface YourMapper {
    TargetEntity toTarget(SourceEntity source);
}

启用这个策略后,当源属性为null时,MapStruct会自动为目标集合属性生成空的可变列表(如new ArrayList<>()),无需手动编写判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:58:14