`
liuInsect
  • 浏览: 131990 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

spring 中prototype 和 reqeust的区别

阅读更多

 

 

我们知道,spring有singleton和prototype作用域,而且从spring2.0开始,又增加了三种作用域,request、session、global session。session、global session的作用域是HTTP session和全局session。对于request和prototype,每一次请求都会产生一个新的bean实例,那么它们的具体有什么区别呢?而且,Spring不能对一个prototype bean的整个生命周期负责,这一点我不太能理解,这样它占用的资源就很高昂了,那么prototype的好处是什么?要结束它的生命周围,要怎么做?而且,感觉request和prototype,除了prototype的生命周期不会被回调以外,它们的作用是不是一样?有什么具体的区别呢?

采纳的答案

2008-08-22 wangxin0072000 (高级程序员)

request依赖于web应用,request就类似与你的servlet,多个用户访问一个servlet,当然是访问servlet的多个实例,prototype实际上是new出来的,你想想,你的bean里new了一个对象,为什么要让spring给你销毁。prototype没有什么好不好的,只不过它能做singleton所不能做得(创建多个实例),在web项目之外也可以做request所不能做得事。prototype的销毁你不必关心,调用它的bean销毁了,它也就销毁了。request是web里所特有的。看来是java web做多了

提问者对于答案的评价:
谢谢了

 

 

 

这是转自 http://www.iteye.com/problems/3104 的文章..这里面只说到了 "request是web里所特有的

而我正好做到类似的应用  自己测试了下.... 把scope改成 reqeust 在struts2接受请求时是会报错的...大概的意思是不能将action和scope(作用域)是request的bean 结合使用,  其实我们用request或者prototype 的目的很明确,就是为了保证action的线程安全,因为spring默认的 scope是 singleton 单例模式的,, 

 

然后我将scope改成prototype 后,action变成线程安全的了.就是每次访问都是新的实例,这点我测试过,能确定,

但这就让我产生一个疑问?  什么时候才可以用request??他和prototype 的区别是???????  请高人回答

 

 

 

 

 

 

 

 

0
0
分享到:
评论
1 楼 ouchuquan 2016-05-05  
Prototype creates a brand new instance everytime you call getBean on the ApplicationContext. Whereas for Request,
only one instance is created for an HttpRequest. So in a single HttpRequest, I can call getBean twice on Application
and there will ever be one bean instantiated, whereas that same bean scoped to Prototype in that same single
HttpRequest would get 2 different instances.

HttpRequest scope
Mark mark1 = context.getBean("mark");
Mark mark2 = context.getBean("mark");
mark1 == mark2; //This will return true

Prototype scope

Mark mark1 = context.getBean("mark");
Mark mark2 = context.getBean("mark");
mark1 == mark2; //This will return false

相关推荐

Global site tag (gtag.js) - Google Analytics