Reputation: 41
I was wondering if it is possible to chain @ModelAttribute methods by having an @ModelAttribute annotated, but not request mapped, method use another ModelAttribute in the method signature. This would be in a controller.
ie
@ModelAttribute("attrOne")
public AttrOne getAttrOne() {
return service.getAttOne();
}
@ModelAttribute("attrTwo")
public AttrTwo getAttrTwo(@ModelAttribute("attrOne") AttrOne attrOne){
return anotherservice.getAttrTwo(attrOne);
}
Then if there was a request mapped method that did this:
@RequestMapping(method=RequestMethod.GET)
public String doSomething(@ModelAttribute("attrTwo") AttrTwo attrTwo )
would this work?
I seem to get a null object for AttrOne in the second annotated method... as the first annotated method is not called by the second one...
Cheers
Upvotes: 4
Views: 1298
Reputation: 1638
According to SPR-6299, this will be possible in Spring 4.1 RC1 or later.
Upvotes: 1
Reputation: 7868
I ran into the same situation by learning from the spring documention:
@ModelAttribute is also used at the method level [..]. For this usage the method signature can contain the same types as documented above for the @RequestMapping annotation.
I found SPR-6299 which faces this problem. In the comments you can find a workaround by providing only one @ModelAttribute annotated method which sets the attributes into the model:
@ModelAttribute
public void populateModel(Model model) {
model.addAttribute("attrOne", getAttrOne());
model.addAttribute("attrTwo", getAttrTwo());
}
Upvotes: 4