在下面的场景中,我如何才能将接口作为ModelAttribute呢?
@GetMapping("/{id}")
public String get(@PathVariable String id, ModelMap map) {
map.put("entity", service.getById(id));
return "view";
}
@PostMapping("/{id}")
public String update(@ModelAttribute("entity") Entity entity) {
service.store(entity);
return "view";
}上面的片段给出了以下错误
BeanInstantiationException: Failed to instantiate [foo.Entity]: Specified class is an interface我不希望spring为我实例化entity,我想使用map.put("entity", ..)提供的现有实例。
发布于 2016-10-14 13:41:04
正如注释中指出的那样,Entity实例在get和post请求之间无法存活。
解决办法是
@ModelAttribute("entity")
public Entity entity(@PathVariable String id) {
return service.getById(id);
}
@GetMapping("/{id}")
public String get() {
return "view";
}
@PostMapping("/{id})
public String update(@ModelAttribute("entity") Entity entity) {
service.store(entity);
return "view";
}这里发生的是,Entity在update中绑定到从@ModelAttribute注释的entity方法创建的Entity。然后Spring将表单值应用于现有对象。
https://stackoverflow.com/questions/40042894
复制相似问题