http://lavasoft.blog.51cto.com/62575/1394669/
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:
Package com.lavasoft.demo.web.controller.lsh.ch5;
Import Org.springframework.context.annotation.Scope;
Import Org.springframework.stereotype.Controller;
Import Org.springframework.ui.ModelMap;
Import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by Administrator on 14-4-9.
*
* @author leizhimin 14-4-9 10:55
*/
@Controller
@RequestMapping ("/demo/lsh/ch5")
@Scope ("prototype")
public class Multviewcontroller {
private static int st = 0; of static
private int index = 0; Non-static
@RequestMapping ("/show")
Public String Toshow (Modelmap model) {
User user = new user ();
User.setusername ("Testuname");
User.setage ("23");
Model.put ("user", user);
return "/lsh/ch5/show";
}
@RequestMapping ("/test")
Public String test () {
System.out.println (st++ + "|" + index++);
return "/lsh/ch5/test";
}
}
0 | 0
1 | 1
2 | 2
3 | 3
4 | 4
To a single case:
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. If you have to define a non-static member variable, set it to a multiple-case mode by annotating @scope ("prototype")
Go: "Spring MVC controller Singleton Trap"