You need to enable JavaScript to run this app. Dozer Java API实现ReportedIssue到Issue单向自定义映射方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

Dozer Java API实现ReportedIssue到Issue单向自定义映射方案咨询

疑问一:自定义转换器的必要性及优化方案

你当前的场景下自定义转换器是合理的:你的映射逻辑里除了info是同名字段可以自动映射外,其余字段要么需要动态生成(refId、reportedOn),要么需要依赖外部服务/工具类计算(type、reporter),这些逻辑Dozer的默认字段映射规则无法处理,必须自定义转换逻辑。

不过你当前的实现有两个可以优化的点,更符合Dozer规范:

  1. 不要在convertTo方法里直接new新的Issue对象,应该优先使用传入的destination对象,避免Dozer已经初始化的对象属性被覆盖,同时修正info字段的取值来源:
@Override
public Issue convertTo(ReportedIssue source, Issue destination) {
    // 优先用传入的目标对象,为空再新建
    Issue issue = destination == null ? new Issue() : destination;
    issue.setRefId(UUID.randomUUID().toString());
    issue.setType(IssueUtils.determineType(source));
    issue.setReportedOn(DateTimeUtils.nowInUTC());
    issue.setReporter(authService.currentUser());
    // 原实现错误取了destination的info,应该取源对象的info值
    issue.setInfo(source.getInfo());
    return issue;
}
  1. 如果你不想写全量的类转换器,也可以用Dozer的Java API配置部分映射,把info的同名字段映射交给Dozer自动处理,整体逻辑更轻量化:
BeanMappingBuilder builder = new BeanMappingBuilder() {
    @Override
    protected void configure() {
        mapping(ReportedIssue.class, Issue.class)
            // 同名字段info自动映射
            .fields("info", "info")
            // 绑定自定义转换器处理剩余特殊字段
            .useCustomConverter(ReportedIssueConverter.class);
    }
};
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.addMapping(builder);

疑问二:单向转换的实现方案

你当前在convertFrom方法中抛出UnsupportedOperationException的用法是完全正确的,这也是Dozer官方推荐的单向转换实现方式——Dozer本身没有提供单独的单向转换器接口,所有自定义转换器都需要实现双向方法,不需要的方向直接抛出该异常即可。

如果你不想每个单向转换器都重复写抛异常的逻辑,可以自己封装一个通用的单向转换器父类,简化后续开发:

public abstract class OneWayDozerConverter<A, B> extends DozerConverter<A, B> {
    protected OneWayDozerConverter(Class<A> prototypeA, Class<B> prototypeB) {
        super(prototypeA, prototypeB);
    }

    @Override
    public A convertFrom(B source, A destination) {
        throw new UnsupportedOperationException("This converter only supports one-way mapping from " 
            + prototypeA.getSimpleName() + " to " + prototypeB.getSimpleName());
    }
}

后续你的单向转换器直接继承这个父类,只需要实现convertTo方法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 00:36:07