我有一个对象,它的构造函数中有一个属性,这个属性是动态创建的,依赖于它接收的另一个对象。
public Booking(Customer customer, Barber barber, LocalDateTime startTime, Service service) {
this.customer = customer;
this.barber = barber;
this.startTime = startTime;
this.service = service;
this.endTime = null;
this.calculateEndTime();
}
public void calculateEndTime(){
int duration = this.service.getDuration();
this.setEndTime(this.startTime.plusMinutes(duration));
}当我通过实现ApplicationRunner的数据存储器启动数据时,我的预订是用endTime创建的。然而,当我通过失眠发布一个新的预订时,这个calculateEndTime()函数没有运行,我的endTime就会以null的身份停留。
据我所知,这是因为spring查看了创建新对象的默认空构造函数和setter。
所以我的问题是,为什么它要通过数据加载程序工作,我如何通过前端/失眠发布一个新的预订来生成它呢?
我尝试在endTime设置器中调用此函数,但这不起作用。
通过数据加载器进行种子数据的示例:
@Component
public class DataLoader implements ApplicationRunner {
@Autowired
BarberRepository barberRepository;
@Autowired
CustomerRepository customerRepository;
@Autowired
BookingRepository bookingRepository;
@Autowired
ServiceRepository serviceRepository;
public DataLoader() {
}
public void run(ApplicationArguments args) {
Service beardTrim = new Service("Beard Trim", 5.00, 10);
serviceRepository.save(beardTrim);
Barber alan = new Barber("Alan");
barberRepository.save(alan);
Customer customer1 = new Customer("Joe");
customerRepository.save(customer1);
LocalDateTime startTime = LocalDateTime.of(2018, Month.NOVEMBER, 5, 12, 00);
Booking booking1 = new Booking(customer1, alan, startTime, beardTrim);
bookingRepository.save(booking1);
}我试图通过失眠症发布数据的例子:
{
"startTime": "2018-11-12T09:00",
"barber": "http://localhost:8080/api/barbers/1",
"service": "http://localhost:8080/api/services/1",
"customer": "http://localhost:8080/api/customers/1"
}谢谢
发布于 2018-11-15 13:31:03
解决这个问题的方法是编写一个定制的post路由,在保存对象之前可以在该对象上调用calculateEndTime()。
发布于 2019-01-08 10:52:04
一个较短的解决方案是使用@prePersist注释,而不是编写自定义postrout。
我的70多行自定义帖子被缩减为一个if语句,它与@prePersist一起使用。
https://stackoverflow.com/questions/53298063
复制相似问题