我正在重构我的代码。我想在我的 DTO 中使用 java 记录而不是 java 类。要将 DTO 转换为实体,我使用的是 ModelMapper(版本 2.3.5)。当我尝试获取有关用户的信息(调用方法将实体转换为 DTO)时,我收到此错误。
Failed to instantiate instance of destination xxx.UserDto. Ensure that xxx.UserDto has a non-private no-argument constructor.
这是我的代码。
public record UserDto(String firstName,
String lastName,
String email,
String imageUrl) {}
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private ModelMapper modelMapper;
@GetMapping("/user/me")
@PreAuthorize("hasRole('USER')")
public UserDto getCurrentUser(@CurrentUser UserPrincipal userPrincipal) {
return convertToDto(userRepository.findById(userPrincipal.getId())
.orElseThrow(() -> new ResourceNotFoundException("User", "id", userPrincipal.getId())));
}
private UserDto convertToDto(User user) {
UserDto userDto = modelMapper.map(user, UserDto.class);
return userDto;
}
private User convertToEntity(UserDto userDto) throws Exception {
User post = modelMapper.map(userDto, User.class);
return post;
}
}
编辑:更新到版本2.3.8
没有帮助!