简体   繁体   中英

Spring @ModelAttribute interface

How can I have an interface as a ModelAttribute as in the below scenario?

@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";
}

Above snippet gives the follow errors

BeanInstantiationException: Failed to instantiate [foo.Entity]: Specified class is an interface

I don't want spring to instantiate entity for me, I want to use the existing instance provided by map.put("entity", ..) .

As been pointed out in comments, the Entity instance does not survive between the get and post requests.

The solution is this

@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";
}

What happens here is that the Entity in update binds to the Entity created from the @ModelAttribute annotated entity method. Spring then applies the form-values to the existing object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM