您可以创建一个映射器并将您的实体对象映射到将发送到您的前端的 DTO。
由于您没有为您的日期指定您使用的类,我将使用LocalDate 作为示例,但可以将相同的逻辑应用于您的日期类。
假设您的实体类如下所示:
public class SampleEntity {
private LocalDate localDate;
}
您的 DTO 类将如下所示:
public class SampleDto {
// the Jackson annotation to format your date according to your needs.
@DateTimeFormat(pattern = "DD-MM-YYYY")
private LocalDate localDate;
}
然后您需要创建映射器以从 SampleEntity 映射到 SampleDto,反之亦然。
@Component
public class SampleMapper {
public SampleDto mapTo(final SampleEntity sampleEntity){
// do the mapping
SampleDto sampleDto = new SampleDto();
sampleDto.setLocalDate(sampleEntity.getLocalDate());
return sampleDto;
}
public SampleEntity mapFrom(final SampleDto sampleDto){
// do the mapping
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setLocalDate(sampleDto.getLocalDate());
return sampleEntity;
}
}
您可以像这样在控制器中使用所有这些:
@GetMapping
public ResponseEntity<SampleDto> exampleMethod() {
// service call to fetch your entity
SampleEntity sampleEntity = new SampleEntity(); // lets say this is the fetched entity
sampleEntity.setLocalDate(LocalDate.now());
SampleDto sampleDto = sampleMapper.mapTo(sampleEntity);
return ResponseEntity.ok(sampleDto);
}
使用此解决方案,您可以避免将 Jackson 注释添加到您的实体中。同样使用此解决方案,您可以准确控制前端可以访问的内容。更多关于这里What is the use of DTO instead of Entity?