首页 > 解决方案 > MapStruct:如何使用 mapstruct 将 String 转换为 byte[]

问题描述

在我的 dto 课程中:

private String password;

在我的模型课上:

private byte[] password;

我想使用 mapStruct 将 String 转换为 byte[]。有人可以帮忙吗

提前致谢。

标签: spring-bootmappingmapstruct

解决方案


最好的方法是为String和之间的映射提供默认方法byte[]

例如:

@Mapper
public MyMapper {

    Model fromDto(Dto dto);

    default byte[] toBytes(String string) {
        return string != null ? string.getBytes() : null;
    }

}

有了这个,您将让 MapStruct 为您之间的所有其他字段自动执行Dto和并将Model映射保留在方法之间。Stringbyte[]toBytes


推荐阅读