What is the purpose and usage of @ModelAttribute in Spring MVC?
I know this is an old thread, but I thought I throw my hat in the ring and see if I can muddy the water a little bit more :)
I found my initial struggle to understand @ModelAttribute was a result of Spring's decision to combine several annotations into one. It became clearer once I split it into several smaller annotations:
For parameter annotations, think of @ModelAttribute as the equivalent of @Autowired + @Qualifier i.e. it tries to retrieve a bean with the given name from the Spring managed model. If the named bean is not found, instead of throwing an error or returning null, it implicitly takes on the role of @Bean i.e. Create a new instance using the default constructor and add the bean to the model.
For method annotations, think of @ModelAttribute as the equivalent of @Bean + @Before, i.e. it puts the bean constructed by user's code in the model and it's always called before a request handling method.
Figuratively, I see @ModelAttribute as the following (please don't take it literally!!):
@Bean("person")
@Before
public Person createPerson(){
return new Person();
}
@RequestMapping(...)
public xxx handlePersonRequest( (@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){
...
}
As you can see, Spring made the right decision to make @ModelAttribute an all-encompassing annotation; no one wants to see an annotation smorgasbord.