SpringMVC Controller singleton and multiple instances

For SpringMVC Controller singleton and multiple instances, an example is given below.
The first time: the class is multi-instance, one normal property and one static property.

 

Result: Normal property: 0......Static property: 0
Normal properties: 0......Static properties: 1
Normal properties: 0 .............Static properties: 2
Normal properties: 0 ...........Static properties: 3
So: for multiple cases, the common attribute will not be shared and will not have an impact, and this attribute will be shared for static attributes.
 
Second time: class changed to singleton

 

 

Result: Normal property: 0......Static property: 0
Normal properties: 1......Static properties: 1
Normal properties: 2......Static properties: 2
Normal properties: 3......Static properties: 3
So: for the singleton case normal properties and static properties will be shared.
 
The third time: the class removes the @Scope annotation

 

 

Result: Normal property: 0......Static property: 0
Normal properties: 1......Static properties: 1
Normal properties: 2......Static properties: 2
Normal properties: 3......Static properties: 3
So: springmvc is a singleton by default.
 
In addition, print in other methods

 

 

The result of the output is

 

 

Jumping to other methods will not take the initial value, but will share this property.
 
Finally: try not to define properties in the controller. If you need to define properties in special cases, then add the annotation @Scope("prototype") to the class and change it to multi-instance mode. Previously, struts was based on class properties. For sending, defining attributes can be common to the entire class, so the default is multiple cases, otherwise multi-threaded access must share the attribute values ​​in the class, which is definitely unsafe, but springmvc is based on method development, all using formal parameters After receiving the value, the parameters at the end of a method are destroyed. Multi-threaded access will generate a memory space, and the parameters inside will not be shared. All springmvc uses a singleton by default, so the controller is not suitable for defining properties in the class, as long as If no properties are defined in the controller, the singleton is completely safe. The main reason why springmvc is designed in this way is to improve the performance of the program and the maintenance of the program in the future is only for the maintenance of the business. If there are too many attributes of struts defined, I don't know which method uses this attribute, and the maintenance of the program in the future is still very troublesome. of

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325296002&siteId=291194637