Using @ModelAttribute to Initialize Model Attributes

Any method inside a controller class that is annotated with the @ModelAttribute annotation is called before the actual request - handling method in the same controller. It can access an instance of the model passed in as a parameter, return a model attribute as described previously, or even combine both methods.

Take a look at the following code example:

@ModelAttribute
public void addDefaultAttributes(Model model) {
int allPostsCount = blogPostService.numberOfBlogPosts();
model.addAttribute("allPostsCount", allPostsCount);
}

This method will add the number of all posts as reported by the numBlogPosts() method for any request that is handled by the controller class.

You can even use @PathParam and similar directives if you require access to such values. For example, this can be useful to query the database.


Using an annotated parameter allows you to pick up only certain attributes that may have been initialized elsewhere. It also enables a handling method to clearly express its purpose. Finally, the controller method doesn't need to fiddle around with the full model.

Having an annotated method allows you to initialize the model with attributes that are generally used in all views and are independent of the current task to be performed. This expresses the principle of separation of concerns.