Does Spring MVC create a new object defined as a ModelAttribute on every call?

java, spring-mvc

Solution

It is NOT a good practise to use Model Attribute as a bean. It is good for manimulating form data before they are persisted into database.

`@ModelAttribute("formAttribute")` is created when you have specified it in your method as parameter:

public void getForm(@ModelAttribute("formAttribute") Form form) {
}

It is created before every method call by calling its contruct:

@ModelAttribute("formAttribute")
public Form getForm() {
   return new Form();
}

When it is not specified in method parameter it doesn't exist.

There is possible to add your `@ModelAttribute` into session by defining `@SessionAttributes` on your controller:

@Controller
@SessionAttributes("formAttribute")
public HelloController

Then it is initialized once, when you firstly use it, and destroyed when you destroy it by calling:

public void finalStep(SessionStatus status) {
   status.setComplete();
}

I think with combination of `@SessionAttributes` it is possible in relatively easy way create the wizard-like flow.

Problem

I am working on a wizard-like set of pages, where the user has to enter bits of data in several views for a final submission, allowing them to go back-and-forth prior to the final Submit is done. I was trying to use the same Bean, defined as a ModelAttribute, for all the views, basically just passing this one Bean around like a token in which each view adds its little bit of data. The problem is that Spring MVC seems to create a new Bean on ever call. My admittedly fuzzy understanding about the Model was that it was basically like putting something into session, and that object would be around until the session was done. This does not seem to be the case. So, I guess the first question is...where do Model Attributes "live", and for how long? Is there a better pattern out there for implementing a wizard-like interface using just Spring MVC (I am limited and can't use Web Flow...its not an approved tool where I work)?

Original source