对于 Gunjan 的回答,Spring Boot 中的 Java 配置如下:
将自定义转换器创建为 bean,如下所示:
@Component
public class LoadableFooBeanConverter extends DozerConverter<BarBean, FooBean> {
private final Util util; // Any beans that need to be injected into the custom converter
@Autowired // Constructor Injection
public LoadableFooBeanConverter(Util util) {
super(BarBean.class, FooBean.class);
this.util = util;
}
@Override
public FooBean convertTo(final BarBean source, final FooBean destination) {
// Your logic
}
@Override
public BarBean convertFrom(final FooBean source, final BarBean destination) {
// Your logic
}
}
创建 Mapper 组件并注册自定义转换器,如下所示:
@Component
@RequiredArgsConstructor // lombok annotation
public class DozerMapper {
@Autowired
private final LoadableFooBeanConverter loadableFooBeanConverter;
@Getter // lombok annotation
private Mapper mapper;
@PostConstruct
public void init() {
this.mapper = DozerBeanMapperBuilder.create()
.withMappingBuilders(BarMappingBuilder.builder().build())
.withCustomConverterWithId("loadableFooBeanConverter", loadableFooBeanConverter)
.build();
}
@Builder // lombok annocation
private static class BarMappingBuilder extends BeanMappingBuilder {
@Override
protected void configure() {
mapping(FooBar.class, FooBarFoo.class)
.fields("fooBean", "barBean", FieldsMappingOptions.customConverterId("loadableFooBeanConverter"));
}
}
}