Reputation: 49237
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", ..)
.
Upvotes: 2
Views: 582
Reputation: 49237
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.
Upvotes: 4