The main difference is that one is a method annotation and the other is a statement.
This implies other things. The annotation will expose your object for every request handled by the controller, unless an exception will be thrown and the exception handler fires. The statement will work just for the handler method it's declared in.
There is, of course, also the other way of using the annotation: on a method parameter, which is also the usual way for working with HTML form transport objects.
As for some subjective, opinionated recommendations:
- statement is, I guess, the usual way, as it is rarely that you'd like to expose the same object for all types of requests handled by a particular controller
- annotation on a method return value, as in your example, is a nice way of exposing the so called reference data, as mentioned in the documentation – e.g., imagine you have an HTML
<select>
in a form and you want to provide the list of <option>
s in the controller because they must come from some data retrieved from a JPA repository – that's how I used to use it; since this kind of data is usually needed on every type of request handled by a controller (provided that the controller is related to some form), it unclutters your handler methods from repetitively adding the same reference data to the View Model
- annotation on a method parameter is, as previously mentioned, used usually with form transport objects (i.e. bean classes whose fields contain the form data) – in a form view handler method you then use the parameter on it's own, and in a form submission handler method you follow the
@ModelAttribute
annotated parameter with a BindingResult
type parameter