Spring Controllers with Prototype Scope
October 9, 2006 – 20:44 | java, springMost of the time, we configure the controllers in our Spring MVC application to be singletons, because of the their stateless nature. However, being configured as normal Spring beans, Spring controllers can also be declared with the prototype scope. Sometimes, it can actually be quite a useful feature. For instance, in a controller that descends from SimpleFormController, let’s say the formBackingObject() method needs to load an object from the DB that is necessary to instantiate the actual form object, and that same object also will also be used during onSubmit and/or referenceData(). Otherthan either reloading the object later, or resorting to storing the object in the request or even the session, a more convenient, less prone to name space clashing, and arguably more OO approach would be making it an instance variable, and making the controller a prototype bean.
Unlike a singleton controller, a prototype scope controller must have its bean name added to the ‘mappings’ property of the SimpleUrlHandlerMapping bean, instead of the ‘urlMap’ property, which requires an actual bean reference. The small price here is that, since the bean name is textually added to the mapping, there won’t be any XML validation against it. (In fact, I don’t think Spring IDE would catch an invalid bean name here either.)

3 Responses to “Spring Controllers with Prototype Scope”
Why don’t you put the object you’ve loaded from the DB into the form-backing object in the first place? There will be no name space clashing as Spring MVP handles storing the form-backing object into the request or session and retireving it from there.
Just my 0.02 EUR
Regards
Fokko
By F. Degenaar on Oct 10, 2006
Hi Fokko,
Well, it’s just one of the scenarios I picked as an example. A SimpleFormController, together with its superclasses, provides numerous overriding points, some of which don’t necessarily have the visibility to the form backing object.
That being said, sure, what you are suggesting can be another viable approach. Although we can only do that when the form backing object is not an actual domain object which we wouldn’t want to arbitrarily “stuff up”
.
Thanks!
–Jing
By Jing Xue on Oct 10, 2006
Hi-ya Everyone,
I just wanted to share this bankruptcy information resource.
I’ve been searching the www digging for answers to my bankruptcy questions but personal bankruptcy info
is hard to dig up…. Thus far the best site I have found is http://www.bankruptcyinformation.biz .
There is a feature on the site that allows you to ask questions and get answers from real bankruptcy experts.
Best Regards..
By irrivyPax on Oct 10, 2009