Go: "Spring MVC controller Singleton Trap"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.