如何以编程方式为推土机设置自定义转换器?以下代码不起作用:
自定义转换器实施:
class ConverterImpl extends DozerConverter<A, B> {
ConverterImpl() {
super(A.class, B.class);
}
@Override
public B convertTo(A source, B destination) {
return destination;
}
@Override
public A convertFrom(B source, A destination) {
return destination;
}
}
测试代码:
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomConverters(Collections.<CustomConverter>singletonList(new ConverterImpl()));
A a = new A();
B b = mapper.map(a, A.class);
运行上面的代码后,不会调用自定义转换器。怎么了?
答案 0 :(得分:4)
看起来您必须实际添加特定的映射,遗憾的是,您只能使用编程API指定字段级转换器,而不是类级转换器。因此,如果将A和B类包装在容器类中,则可以为A和B字段指定映射。
例如,以下详细代码按预期工作:
public class DozerMap {
public static class ContainerA {
private A a;
public A getA() { return a; }
public void setA(A a) { this.a = a; }
}
public static class ContainerB {
private B b;
public B getB() { return b; }
public void setB(B b) { this.b = b; }
}
private static class A { };
private static class B { };
static class ConverterImpl extends DozerConverter<A, B> {
ConverterImpl() {
super(A.class, B.class);
}
@Override
public B convertTo(A source, B destination) {
Logger.getAnonymousLogger().info("Invoked");
return destination;
}
@Override
public A convertFrom(B source, A destination) {
Logger.getAnonymousLogger().info("Invoked");
return destination;
}
}
public static void main(String[] args) {
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomConverters(Collections.<CustomConverter> singletonList(new ConverterImpl()));
BeanMappingBuilder foo = new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(ContainerA.class, ContainerB.class).fields("a", "b", FieldsMappingOptions.customConverter(ConverterImpl.class));
}
};
mapper.setMappings(Collections.singletonList(foo));
ContainerA containerA = new ContainerA();
containerA.a = new A();
ContainerB containerB = mapper.map(containerA, ContainerB.class);
}
}
答案 1 :(得分:1)
为什么要以编程方式设置它?我的意思是你有什么具体需求吗?否则,通过xml文件进行映射可以正常工作。
如果您希望以编程方式执行更多操作,而不是通过某些xml配置文件,请查看Orika。
它具有良好的API支持。