【发布时间】:2020-01-04 12:41:32
【问题描述】:
我有我的@RestController,他的参数映射到@ModelAttribute 以缩短参数列表。但是,某些属性必须转换为自定义对象(即 Long -> Instant)。我的问题是有没有办法让 spring 使用我的设置器来设置这些对象?
控制器映射
@GetMapping("/v1/my/path")
public Collection<Dto> getAll(@ModelAttribute MyRequest request) {
return someSevice.doSomething(request);
}
ModelAttribute 类
public class MyRequest {
private Instant startTime;
private Instant endTime;
private ZoneId timezone;
// How can make spring use this setter to set start time?
private void setStartTimeFromLong(Long startTime) {
this.startTime = Instant.ofEpochSecond(startTime);
}
}
【问题讨论】:
-
也许没有办法实现
-
A custom
InitBindereditor 可能是这里最直接的方法。也就是说,由于这是一个GET,通常的模型是“请求”是一组查询参数,我建议检查现有的 Spring 对 Querydsl 作为 MVC 参数的支持。