首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring @ModelAttribute接口

Spring @ModelAttribute接口
EN

Stack Overflow用户
提问于 2016-10-14 12:12:54
回答 1查看 512关注 0票数 2

在下面的场景中,我如何才能将接口作为ModelAttribute呢?

代码语言:javascript
复制
@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";
}

上面的片段给出了以下错误

代码语言:javascript
复制
BeanInstantiationException: Failed to instantiate [foo.Entity]: Specified class is an interface

我不希望spring为我实例化entity,我想使用map.put("entity", ..)提供的现有实例。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-14 13:41:04

正如注释中指出的那样,Entity实例在getpost请求之间无法存活。

解决办法是

代码语言:javascript
复制
@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";
}

这里发生的是,Entityupdate中绑定到从@ModelAttribute注释的entity方法创建的Entity。然后Spring将表单值应用于现有对象。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40042894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档