spring mvc 是否要设置@Scope("prototype")
来源:互联网 发布:中国政治改革知乎 编辑:程序博客网 时间:2024/06/16 06:40
Spring MVC Controller默认是单例的:
单例的原因有二:
1、为了性能。
2、不需要多例。
1、这个不用废话了,单例不用每次都new,当然快了。
2、不需要实例会让很多人迷惑,因为spring mvc官方也没明确说不可以多例。
我这里说不需要的原因是看开发者怎么用了,如果你给controller中定义很多的属性,那么单例肯定会出现竞争访问了。
因此,只要controller中不定义属性,那么单例完全是安全的。下面给个例子说明下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
;
//静态的
private
int
index =
0
;
//非静态
@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
改为单例的:
0 | 0
1 | 0
2 | 0
3 | 0
4 | 0
从此可见,单例是不安全的,会导致属性重复使用。
最佳实践:
1、不要在controller中定义成员变量。
2、万一必须要定义一个非静态成员变量时候,则通过注解@Scope("prototype"),将其设置为多例模式。
只要不定义一个成员变量就行了。就可以不用@Scope("prototype")
本文出处:本文出自 “熔 岩” 博客,请务必保留此出处http://lavasoft.blog.51cto.com/62575/1394669
0 0
- spring mvc 是否要设置@Scope("prototype")
- spring mvc 是否要设置@Scope("prototype")
- spring mvc 设置@Scope("prototype")
- Spring Bean 的 scope属性为何要设置为prototype
- spring scope=prototype
- spring scope="prototype"
- Spring注解@Scope("prototype")
- Spring注解@Scope("prototype")
- Spring注解@Scope("prototype")
- ServiceLocatorFactoryBean spring scope prototype
- spring的scope="prototype"
- spring action scope="prototype"
- spring scope="prototype"属性
- Spring注解之@Scope("prototype")
- Spring Bean 的scope什么时候设置为prototype,什么时候设置为singleton
- SPRING中属性SCOPE的prototype是什么意思
- SPRING中属性SCOPE的prototype是什么意思
- SPRING中属性SCOPE的prototype是什么意思
- softirq原理以及源码分析
- 命令行运行 iOS UI Automation 测试及问题
- hdu 1869 六度分离(floyd)
- 比较好的文章记录
- Android源代码分析(二) MediaScanner源码分析(上)
- spring mvc 是否要设置@Scope("prototype")
- Timer的schedule和scheduleAtFixedRate的区别
- IOS申请真机调试详解
- Java之归并排序算法(一)
- bjfuOJ 1124奶奶的红包(谈递推与递归)
- How to install BigBlueButton 0.9.0-beta
- 学习笔记:Caffe上配置和运行MNIST
- CDialog::Create()创建非模态对话框框,若未销毁造会成内存泄露的解决办法
- VS2010生成exe在别的机子上运行提示“丢失MSVCR100D.dll”