In my Spring 3.1.2.RELEASE application I have a complex form which requires the injection of a predefined bean:
<util:map id="predefinedLocations" map-class="java.util.LinkedHashMap">
<entry key="first address" value="Location A" />
<entry key="another one" value="Location B" />
<!-- ... -->
</util:map>
My form is created as below:
@RequestMapping(value = "/create", method = RequestMethod.GET)
public CreationForm createForm() {
return new CreationForm();
}
I can’t pass the map as a constructor argument of my form because my controller uses @Valid annotation which tries to instantiate the form.
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid CreationForm form, BindingResult formBinding, Model model) {
if (formBinding.hasErrors()) {
// PROBLEM HERE
//
// View rendering fails because a freshly created CreationForm will be
// passed to the view so Spring needs to handle the injection of
// predefinedLocations.
return null;
}
// ...
}
My first idea was to use a form factory but I can’t achieve that in this context.
How can I inject (or reference) the predefinedLocations bean into my form?
I finally found the solution.
The form is now created as below in my controller:
This way,
@Validdoes not instantiate a new form but reuse the previous instance.