1
フィールドマッピングにカスタムロジックを適用する方法は?この例では、LocalDate birthdate
のうちint age
を計算したいとします。modelmapperを使用してフィールドをマッピングするときにカスタムロジックを適用する方法
public class ModelMapperConfigTest {
@Data
public static class Person {
private LocalDate birthdate;
}
@Data
public static class PersonDto {
private long age;
}
// Test data
LocalDate birthdate = LocalDate.of(1985, 10, 5);
long age = 32;
Clock clock = Clock.fixed(birthdate.plusYears(age).atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());
@Test
public void should_calc_age() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
// TODO: How to configure the Mapper so that calcBirthdate is used?
// test that all fields are mapped
modelMapper.validate();
// test that the age is calculated
Person person = new Person();
person.setBirthdate(birthdate);
PersonDto personDto = modelMapper.map(person, PersonDto.class);
assertTrue(personDto.age == age);
}
// This method should be used for mapping. In real, this could be a service call
private long calcBirthdate(LocalDate birthdate) {
return YEARS.between(birthdate, LocalDate.now(clock));
}
}