The Spring MVC controller defaults to Singleton:
There are two reasons for a single case:
1, for performance.
2, do not need many examples.
1, this does not have the nonsense, the single case does not need each time new, certainly fast.
2, do not need an instance will confuse many people, because spring MVC official did not explicitly say can not be many examples.
The reason why I don't need it here is to see how developers use it, and if you define a lot of attributes for the controller, then the Singleton will definitely have a competitive access.
Therefore, the Singleton is completely secure as long as the attribute is not defined in the controller. Here is an example of the following:
PackageCom.lavasoft.demo.web.controller.lsh.ch5;ImportOrg.springframework.context.annotation.Scope;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.ModelMap;Importorg.springframework.web.bind.annotation.RequestMapping;/*** Created by Administrator on 14-4-9. * *@authorleizhimin 14-4-9 Morning 10:55*/@Controller @requestmapping ("/demo/lsh/ch5") @Scope ("Prototype") Public classMultviewcontroller {Private Static intst = 0;//of Static Private intindex = 0;//non-static@RequestMapping ("/show") PublicString toshow (Modelmap model) {User User=NewUser (); User.setusername ("Testuname"); User.setage ("23"); Model.put ("User", user); return"/lsh/ch5/show"; } @RequestMapping ("/test") PublicString Test () {System.out.println (St+ + + "|" + index++); return"/lsh/ch5/test"; }}
0 | 0
1 | 1
2 | 2
3 | 3
4 | 4
To multiple cases:
0 | 0
1 | 0
2 | 0
3 | 0
4 | 0
From this point, the singleton is unsafe and will cause the property to be reused.
Best Practices:
1. Do not define member variables in the controller.
2. In case a non-static member variable must be defined, it is set to a multiple-instance mode by annotating @scope ("prototype").
This article is from the lava blog, so be sure to keep this source http://lavasoft.blog.51cto.com/62575/1394669
Spring MVC Controller Singleton Trap