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

如何配置MapStruct使用ReferenceId的of()工厂方法实例化对象?

解决MapStruct使用私有构造类的静态工厂方法实例化问题

针对你的ReferenceId类(私有构造,仅通过of(UUID id)静态工厂方法实例化),MapStruct报错找不到可访问构造方法的问题,可通过以下几种方式配置:

方法一:使用@ObjectFactory自定义实例创建逻辑

在映射器接口中添加一个被@ObjectFactory标注的默认方法,指定用ReferenceId.of()创建实例:

import org.mapstruct.ObjectFactory;
import org.mapstruct.Mapper;

@Mapper
public interface ReferenceMapper {

    // 其他映射方法定义...

    @ObjectFactory
    default ReferenceId createReferenceId(UUID id) {
        return ReferenceId.of(id);
    }
}

MapStruct在需要实例化ReferenceId时,会自动调用这个方法,替代默认的构造方法调用逻辑。

方法二:通过expression直接指定工厂方法调用

如果是在具体字段映射时需要创建ReferenceId,可以在@Mapping注解中用expression直接指定调用逻辑:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper
public interface YourEntityMapper {

    @Mapping(target = "referenceId", expression = "java( ReferenceId.of(dto.getReferenceUuid()) )")
    YourEntity dtoToEntity(YourDto dto);
}

方法三:用转换器方法+qualifiedByName

定义一个命名转换器方法,再在映射时指定使用该方法:

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;

@Mapper
public interface YourEntityMapper {

    @Named("uuidToReferenceId")
    default ReferenceId uuidToReferenceId(UUID uuid) {
        return ReferenceId.of(uuid);
    }

    @Mapping(target = "referenceId", qualifiedByName = "uuidToReferenceId")
    YourEntity dtoToEntity(YourDto dto);
}

以上三种方式都能让MapStruct绕过私有构造方法,使用你提供的of()静态工厂方法来实例化ReferenceId对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:52:50