controller默认是单例的,单例的是线程不安全的
下面是一个简单的案例:
一、先将idea设置为热部署
1.在pom文件中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
2.file->settings–>compire–>build project automatically
ctrl+shift+alt 勾选
二、简单案列
1.编写controller
package cn.mrhan.java.thread;
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
public class ThreadController {
private int num = 0;
@RequestMapping("/test1")
@ResponseBody
public String test1(){
return ++num +"";
}
@RequestMapping("/test2")
@ResponseBody
public String test2(){
return ++num +"";
}
}
2.启动程序
访问http://localhost:8080/test1 可以看到结果为1
再次访问或访问http://localhost:8080/test2 可以看到结果为2
这意味着不同的线程得到的结果不同 所以 单例是不安全的
3.修改controller类 加上prototype注解: 原型模式,每次通过getBean获取该bean就会新产生一个实例,创建后spring将不再对其管理;
package cn.mrhan.java.thread;
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")
public class ThreadController {
private int num = 0;
@RequestMapping("/test1")
@ResponseBody
public String test1(){
return ++num +"";
}
@RequestMapping("/test2")
@ResponseBody
public String test2(){
return ++num +"";
}
}
4.再次访问http://localhost:8080/test1 http://localhost:8080/test2
可以看到页面显示的都是1(由于设置了热部署 因此不需要再次启动)