案例代码
@Controller
@RequestMapping("/index")
@Scope("prototype")
public class TestControler {
final ThreadLocal<RestBean> local = new ThreadLocal<>();
@Autowired
RestBean bean;
@RequestMapping("/setParam.do")
public void setParam(HttpServletRequest requestInfo){
String parameter = requestInfo.getParameter("id");
// RestBean rr= local.get();
// if(rr == null){
// rr = new RestBean();
// }
System.out.println("SetParamValve--now param is:" + bean.getParam());
bean.setParam(parameter);
// local.set(rr);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"GetParamValve--now param is:" + bean.getParam());
}
线程12:SetParamValve--now param is:null
http-bio-8080-exec-12GetParamValve--now param is:fffffffffff
线程3:SetParamValve--now param is:null
http-bio-8080-exec-3GetParamValve--now param is:yyyyy
当设置为prototype时:每次连接请求,都会生成一个bean实例,也会导致一个问题,当请求数越多,性能会降低,因为创建的实例,导致GC频繁,gc时长增加。
设置为单例模式:保证了全局都会有一个实例,对性能有所提高,但是如果实例中有非静态变量时,会导致线程安全问题,共享资源的竞争。
默认是单例模式,即scope="singleton"。另外scope还有prototype、request、session、global session作用域。scope="prototype"多例
@scope默认是单例模式(singleton)
如果需要设置的话@scope("prototype")
1.singleton单例模式,
全局有且仅有一个实例
2.prototype原型模式,
每次获取Bean的时候会有一个新的实例
3.request
session作用域表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效
5.global session
但是一般常见的话一般会使用上面1和2两种