2

我正在使用ModelMapper在对象之间进行直接映射。

ModelMapper mapper = new ModelMapper();
// TypeMap created
mapper.map(sourceObj, destObj);

mapper = new ModelMapper();
// TypeMap is recreated
mapper.map(sourceObj, destObj);

我在源代码中注意到,如果 aTypeMap之间不存在sourceObjdestObj它将缓存TypeMapingetOrCreate方法。

据我所知,此缓存与映射器实例相关联,这意味着如果我必须使用新的 ModelMapper 实例第二次将其映射sourceObjdestObj,则它必须重新创建TypeMap.

我假设这是一个相当昂贵的操作,假设我将一个集合映射sourceObjdestObj. 这使我得出结论,我应该重用 ModelMapper 实例。

这个结论正确吗?

谢谢

4

1 回答 1

8

Yes. There is even a section in the FAQ about this:

Should I reuse my ModelMapper instance?

Unless you need different mappings between the same types, then it’s best to re-use the same ModelMapper instance. If you use a dependency injection container, you can accomplish this by configuring ModelMapper as a singleton.

于 2016-09-20T04:04:58.013 回答