SPRINGMVC Controller Single Case problem

Source: Internet
Author: User

SPRINGMVC controller default is a singleton singleton, specifically can see the annotations scope can be seen at a glance.

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:

@Controller @requestmapping ("/demo")  Public class Multviewcontroller {    privatestaticint st = 0;      // of Static    Private int index = 0;          // non-static        @RequestMapping ("/test")    publicvoid  Test () {        System.out.println (St+ + + "|" + index++);}    }

The default singleton, as the number of requests increases:

0 | 0

1 | 1

2 | 2

3 | 3

4 | 4

...

Controller adds annotations:

@Scope (value = configurablebeanfactory.scope_prototype)

At this point, no matter how many requests, the result is:

0 | 0

1 | 0

2 | 0

3 | 0

4 | 0

...

It is easy to see from the above that the singleton is thread insecure and can result in the reuse of attributes.

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")

SPRINGMVC Controller Single Case problem

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.