Spring MVC Controller默认是单例的:web
单例的缘由有二:spring
一、为了性能。安全
二、不须要多例。mvc
一、这个不用废话了,单例不用每次都new,固然快了。app
二、不须要实例会让不少人迷惑,由于spring mvc官方也没明确说不能够多例。 ide
我这里说不须要的缘由是看开发者怎么用了,若是你给controller中定义不少的属性,那么单例确定会出现竞争访问了。 性能
所以,只要controller中不定义属性,那么单例彻底是安全的。下面给个例子说明下:ui
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 | 0prototype
1 | 1开发
2 | 2
3 | 3
4 | 4
改成单例的:
0 | 0
1 | 0
2 | 0
3 | 0
4 | 0
今后可见,单例是不安全的,会致使属性重复使用。
最佳实践:
一、不要在controller中定义成员变量。
二、万一必需要定义一个非静态成员变量时候,则经过注解@Scope("prototype"),将其设置为多例模式。