开发者

Spring Web MVC and newing up beans

开发者 https://www.devze.com 2023-03-10 03:35 出处:网络
We are working on a Spring 3.0.5 Web MVC-based application. In our code we quite often do something like this:

We are working on a Spring 3.0.5 Web MVC-based application. In our code we quite often do something like this:

@ModelAttribute(ModelKeys.SOME_BEAN)
public SomeBean newSomeBean() {
  return new SomeBean();
}

I think this is not necessary. But if it really wasn't, then I wonder how has th开发者_开发技巧is managed to slip through so many code reviews? In my understanding, if a controller method wanted a NEW SomeBean, then annotating a parameter in that method with @ModelAttribute should be enough? Spring would then use the default constructor to new up the required bean for invoking the controller method, e.g.:

@RequestMapping(method = RequestMethod.POST)
public String doIt(
  @ModelAttribute(ModelKeys.SOME_BEAN) final SomeBean bean,
  final BindingResult bindingResult)
{
  ...
}

here, Spring would new up an instance of SomeBean and try to data-bind into it from the POSTed data, right? There's no need for the method as shown in the first code snippet? Please can you confirm this or provide me with your thoughts on this? Would I be introducing a risk if I just went ahead and removed all these methods that do nothing other than new up an empty bean?


@ModelAttribute annotation on a method does not bind the bean attributes with HTTP request parameters. This is the key difference from the same annotation on a method parameter. Such approach is useful to populate some data that does not depend on request parameters in the model, for instance, values of a comboboxes taken from dictionaries. This is especially helpful, if you have several handler methods in a controller, e.g. to view/change/delete the same type of object and you need the same set of model attributes in all of them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号