如何解决ModelMapper 转换器未实例化目标对象
我正在使用这样的 ModelMapper 转换器:
在 Spring AppContext 中:
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
return modelMapper;
}
然后在控制器中:
@Autowired
public PatientController(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.modelMapper.addConverter(populatePatientDto);
}
Converter<Patient,PatientDTO> populatePatientDto = new Converter<Patient,PatientDTO>() {
@Override
public PatientDTO convert(MappingContext<Patient,PatientDTO> context) {
Patient patient = context.getSource();
PatientDTO patientDTO = context.getDestination();
patientDTO.setGender1(patient.getGender().getCode());
return patientDTO;
}
};
我是这样使用的:
@GetMapping("/patients/{id}")
PatientDTO getPatient(@PathVariable Long id) {
Patient patient = repository.findById(id).orElseThrow(() -> new PatientNotFoundException(id));
return modelMapper.map(patient,PatientDTO.class);
}
但是转换器失败(出现空指针异常),因为 context.getDestination() 为空。如果我在转换器中创建一个 PatientDTO 对象,一切都会按预期工作。
我认为 ModelMapper 转换器会自动创建目标对象。这样对吗?我看过的示例或文档似乎都没有表明需要显式创建目标对象。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。