【发布时间】:2021-11-19 14:46:15
【问题描述】:
所以我的这位同事创建了一个简单的映射器,我想为其添加更多功能。 我怀疑 mapStruct 将无法为它自动生成方法,所以我相信我将不得不编写自定义映射逻辑。我想将嵌套在输入对象中并保存在键值对结构中的值映射到输出的属性。
- 我是否正确假设我需要编写自定义映射器?
- 我可以将我的自定义映射逻辑附加到他现有的直接映射器吗?
- 还是我必须用新的自定义映射器完全替换他的映射器?
这里是手头的那种结构的一个例子。 他为成员一、二和三实现了映射,我想为成员 alpha 和 beta 添加映射。
@Mapper()
public interface AMapper {
@Mapping(source = "one", target = "oneX")
@Mapping(source = "two", target = "twoX")
@Mapping(source = "three", target = "threeX")
OutA inAToOutA(InA inA);
}
class InA {
String one;
int two;
long three;
InB b;
}
class InB {
List<InC> listOfC = new ArrayList<>();
public InB() {
listOfC.add(new InC("alpha", "AlphaContent"));
listOfC.add(new InC("beta", "BetaContent"));
}
}
class InC {
String key;
String value;
public InC(String key, String value) {
this.key = key;
this.value = value;
}
}
class OutA {
String oneX;
int twoX;
long threeX;
String alphaX;
String betaX;
}
在我的 mapStruct 菜鸟头脑中,解决方案可能看起来像这样, 但我宁愿不必重写他所有的东西,因为它比这个例子更大, 这就是我寻求建议的原因:
@Mapper()
public interface AMapper {
default OutA getA(InA a) {
if (a == null)
return null;
OutA oa = new OutA();
oa.setOneX(a.getOne());
oa.setTwoX(a.getTwo());
oa.setThreeX(a.getThree());
for (InC c : a.getB().getListOfC()) {
switch (c.getKey()) {
case "alpha":
oa.setAlphaX(c.getValue());
break;
case "beta":
oa.setBetaX(c.getValue());
break;
default:
break;
}
}
return oa;
}
}
【问题讨论】:
标签: java customization mapstruct