Issue
I have ran into a problem with adding class with definition of custom PropertyMap to model mapper. Everthing is working as long as I have the mappings added in @PostConstruct of a class that I'm using. On the other hand when I'm moving this to new class where I want to have all PropertyMaps added it seems no to added to model mapper.
With this configuration everything is working fine. RestCompanyDto has object RestAddressDto and when I'm using map function from model mapper the internal object is converted correctly.
@Service
@RequiredArgsConstructor
public class RestOrganizationService {
private final ModelMapper modelMapper;
private final RestAddressDtoMap addressDtoMap;
@PostConstruct
public void mapperConfig() {
modelMapper.addMappings(addressDtoMap);
}
private OfficeDto map(Long id, RestOfficeDto restOfficeDto){
OfficeDto officeDto = modelMapper.map(restOfficeDto, OfficeDto.class);
officeDto.setId(id);
return officeDto;
}
On the other hand when I remove the @PostConstructor from RestOrganizationService and move it to new class the mapping of address object is not working.
@Configuration
@AllArgsConstructor
public class EPRestMapperConfig {
private final ModelMapper modelMapper;
private final RestAddressDtoMap restAddressDtoMap;
@PostConstruct
public void init() {
modelMapper.addMappings(restAddressDtoMap);
}
}
Here is additional code of PropertyMap
@Service
public class RestAddressDtoMap extends PropertyMap<RestAddressDto, AddressDto> {
private CityRepository cityRepository;
private CityServiceImpl cityService;
public RestAddressDtoMap(CityRepository cityRepository, CityServiceImpl cityService){
super(RestAddressDto.class, AddressDto.class);
this.cityRepository = cityRepository;
this.cityService = cityService;
}
@Override
protected void configure() {
using(getCityDto).map(source.getCityId()).setCity(null);
}
private final Converter<Long, CityDto> getCityDto = context ->
(context.getSource() != null
? cityService.toDto(cityRepository.findOne(context.getSource()))
: null);
}
Solution
In you case I recommend to use the following approach:
@Configuration
public class EPRestMapperConfig {
@Bean
public ModelMapper modelMapper(RestAddressDtoMap restAddressDtoMap) {
return new ModelMapper().addMappings(restAddressDtoMap);
}
@Bean
public RestAddressDtoMap restAddressDtoMap() {
return new RestAddressDtoMap();
}
}
I like that style of bean creation, because you can see required dependencies between beans and set required components during bean creating process.
Answered By - saver
Answer Checked By - Willingham (JavaFixing Volunteer)