spring原型与单实例

来源:互联网 发布:手机游戏java通用版 编辑:程序博客网 时间:2024/05/16 14:47

spring中bean默认是单实例模式,如果想每次向上下文请求时,得到一个不同的实例,可以设置为原型模式。通过设置bean的属性值singleton/scope。

那么什么时候用singleton,什么时候用scope呢?跟引入的dtd文件相关,spring手册有如下说明:

If you are referencing the 'spring-beans.dtd' DTD in a bean definition file(s), and you are being explicit about the lifecycle scope of your bean(s) you must use the "singleton" attribute to express the lifecycle scope (remembering that the singleton lifecycle scope is the default). If you are referencing the 'spring-beans-2.0.dtd' DTD or the Spring 2.0 XSD schema, then you will need to use the "scope" attribute (because the "singleton" attribute was removed from the definition of the new DTD and XSD files in favour of the "scope" attribute).

To be totally clear about this, this means that if you use the "singleton" attribute in an XML bean definition then you must be referencing the 'spring-beans.dtd' DTD in that file. If you are using the "scope" attribute then you must be referencing either the 'spring-beans-2.0.dtd' DTD or the 'spring-beans-2.0.xsd' XSD in that file.

0 0
原创粉丝点击