NullPointerException when trying to define a custom PropertyMap

女生的网名这么多〃 提交于 2019-11-29 14:55:28

I think this is ultimately due to the fact that ModelMapper can not instantiate TimeZone objects (nor LocalDateTime etc.) at the time of configuring the mapper.

Actually you don't have to configure anything.

ModelMapper mapper = new ModelMapper();

Foo foo = new Foo();
foo.setTimeZone(TimeZone.getDefault());

FooModel model = mapper.map(foo, FooModel.class);
System.out.println(model.getTimeZoneId()); // "Europe/Berlin" here

This works for me. ModelMapper found out that you want to map the TimeZone's property ID to FooModel's property timeZoneId.

Nevertheless, just in case you want to do that manually: Following the docs quickly, I found the concept of converters. Using a Converter which converts TimeZone to String you can do this:

ModelMapper mapper = new ModelMapper();
TypeMap<Foo, FooModel> typeMap = mapper.createTypeMap(Foo.class, FooModel.class);
Converter<TimeZone, String> tzConverter = ctx -> ctx.getSource().getID() + "!!!";
typeMap.addMappings(map -> {
    map.using(tzConverter).map(Foo::getTimeZone, FooModel::setTimeZoneId);
});

Foo foo = new Foo();
foo.setTimeZone(TimeZone.getDefault());

FooModel model = mapper.map(foo, FooModel.class);
System.out.println(model.getTimeZoneId()); // "Europe/Berlin!!!" here

Autowire using constructor like

public FooConverter(ModelMapper modelMapper){
   this.modelMapper = modelMapper;
}

also make sure your ModelMapper bean has been defined in your spring config class like below:

@Bean
public ModelMapper modelMapper() {
    return new ModelMapper();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!