ModelMapper with Spring, where to put explicit mappings?
Asked Answered
T

1

9

I'm using ModelMapper with Spring. In my controller class I'm autowiring the ModelMapper bean:

@Autowired
private ModelMapper mapper;

I want to do an explicit mapping between my model class and my DTO in my controller methods, something like:

modelMapper.addMappings(mapper -> {
  mapper.map(src -> src.getBillingAddress().getStreet(),
      Destination::setBillingStreet);
  mapper.map(src -> src.getBillingAddress().getCity(),
      Destination::setBillingCity);
});

And then use the mapper to map the classes.

My question is, is it right to add explicit mappings in every controller method call? Will object modelMapper start to grow in memory size?

Other solution is to add the mapping only one time when ModelMapper bean is created, but I don't think that putting mapping logic in a bean configuration is a good decision.

Torsk answered 23/9, 2018 at 1:30 Comment(1)
Thanks for the question. Was working on a feature required ModelMapper and couldn't decide whether to use spring bean or simple object creation because of the very same reason you described.Manofwar
L
5

It is totally fine to setup the mapping logic in the bean configuration of ModelMapper. Mapping is the actual task of that class, so it should be configured when it is created.

Nevertheless, I prefer to create multiple dedicated mapper definitions, one for each type or group of related types.

Doing it this way keeps the configuration aspect separate from the actual usage of the mapper in the controllers - without creating a big pile of unrelated mapping configuration code in one class. Indeed, configuring the mapper in each controller would violate principles like DRY (don't repeat yourself) and SoC (separation of concerns).

In your case (singleton ModelMapper) you may create @Configuration-annotated classes for each type or group of types you want to map. Within that class you would receive the ModelMapper and add the type mappings. Add your configuration code to either

  • a ModelMapper-receiving constructor or
  • a @PostConstruct-annotated method which accesses an @Autowired ModelMapper attribute.

I haven't used ModelMapper myself yet but after peeking into its codebase I would guess that if you follow your original approach, the memory usage would not increase but you would find exceptions about duplicate mappings getting thrown.

Landlordism answered 23/9, 2018 at 2:23 Comment(3)
Could you take a look at this question please? #53287950Tombola
Could you explain more about 'create @Configuration-annotated classes for each type'? In each of these configuration file, we will have a function with '@Bean' annotation that return a model mapper object? Do you have any example?Garman
"Within that class you would receive the ModelMapper", who is invoking and passing the model mapper to this configuration class?Garman

© 2022 - 2024 — McMap. All rights reserved.