2

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", ..).

8
  • Have you feelup entity object on view side ? Commented Oct 14, 2016 at 12:19
  • Thymeleaf form: <form th:object="${entity}">..</form> Commented Oct 14, 2016 at 12:20
  • ok that is correct , and make sure your property names in that entity class is the same name with th:field Commented Oct 14, 2016 at 12:22
  • @JohanSjöberg Is the entity stored in the session? Otherwise it wouldn't survive a request/response cycle. Commented Oct 14, 2016 at 12:29
  • @Kayaman no it's not. Good to know. Commented Oct 14, 2016 at 12:32

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.