1、springmvc controller默认是单例的
当controller被实例化之后,整个容器中只会有一个实例。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class AdminController {
private int x = 1;
private static int y = 1;
@RequestMapping("/test")
@ResponseBody
public String test(){
System.out.println("x="+(x++));
System.out.print(" y="+(y++));
return "success";
}
}
运行多次之后,结果如下:
2、将代码修改,在controller上添加@Scope("prototype")注解之后
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@Scope("prototype")
@RequestMapping("/")
public class AdminController {
private int x = 1;
private static int y = 1;
@RequestMapping("/test")
@ResponseBody
public String test(){
System.out.print("x="+(x++));
System.out.print(" y="+(y++));
System.out.println();
return "success";
}
}
运行多次之后,结果如下:
prototype在每次调用controller时都会创建一个新的实例,所以x的值一直都是1,而y是静态变量,静态变量跟实例是无关的,只跟类有关,是所有对象共有的,所以每运行一次,y的值都会改变