我怎么能创建一个自定义推土机初始化程序

时间:2017-12-04 13:23:30

标签: java spring-boot dozer

是否可以创建自定义的dozer初始值设定项,以便它接受带有构造函数的参数而不只是一个空的构造函数?

例如,下一个转换器失败,因为推土机无法初始化它,并抛出 java.lang.InstantiationException

public class MyCustomDozerConverter extends DozerConverter<MyObject, String> {

    private static String myParameter;

    // How could dozer accepts this constructor?
    public MyCustomDozerConverter(String myParameter) {
        super(MyObject.class, String.class);
        this.myParameter = myParameter;
    }

    @Override
    public String convertTo(MyObject source, String destination) {      
        // Using value of myParamter which passed in constructor
        // business logic
        return destination;
    }

    @Override
    public MyObject convertFrom(String source, MyObject destination) {
        // business logic
        return null;
    }
}

此外,如果可能,那么如何将此参数发送给构造函数,以便它是动态的而不是静态的?

注意:我在spring-boot项目中使用dozer

1 个答案:

答案 0 :(得分:0)

在配置类中,您需要添加此部分:

@Bean
public DozerBeanMapper mapper() throws IOException {
    List<String> mappingFiles = new ArrayList<String>();
    List<CustomConverter> customConverters = new ArrayList<CustomConverter>();
    customConverters.add(new MyCustomDozerConverter(""));

    DozerBeanMapper mapper = new DozerBeanMapper();
    mapper.setMappingFiles(mappingFiles);
    mapper.setCustomConverters(customConverters);

    return mapper;
}

这样,推土机将使用您在mapper.setCustomConverters(customConverters)方法中设置的MyCustomConverter实例。