Spring
中的对象scope
属性表示是对象可以生存的范围,有以下几种取值:
singleton
单例作用域,也是Spring
的默认scope
值。在整个IOC
容器的生命周期中,最多只会创建出一个对象实例,任何需要该对象的地方,都是引用的这一个实例。
这在设计模式中,就是典型的“单例模式”。
<bean id="accountService" class="com.something.DefaultAccountService"/>
<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
prototype
原型作用域,它的意思是每次需要该对象的时候,IOC
容器都会创建一个新的对象实例,不会复用以前创建的对象。
这在设计模式中,就是典型的“原型模式”。
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
request
请求作用域,这种作用域只存在于Spring Web
应用中,是专门针对http
请求设计的,为每个http
请求创建新的对象实例,并且该实例只在当次请求范围内有效。
<bean id="loginAction" class="com.something.LoginAction" scope="request"/>
session
会话作用域,这还是只存在于Spring Web
应用中的作用域,是针对cookies-session
机制设计的,对象的生命周期限定在session
范围内。
<bean id="userPreferences" class="com.something.UserPreferences" scope="session"/>
application
应用作用域,这也是针对Spring Web
应用的,针对的是Servlet
应用上下文,也就是ServletContext
对象实例,这种作用域就是绑定到这个实例上的。
<bean id="appPreferences" class="com.something.AppPreferences" scope="application"/>
websocket
这种作用域也是针对Spring Web
应用的,只不过这里针对的通信协议是WebSocket
协议,不是Http
协议,这两种协议的区别就不展开了。采用这种作用域的对象,生命周期限定在WebSocket
范围内,其实它和request
作用域挺像的,都是站在通信协议的角度看Spring
对象生命周期的。
SimpleThreadScope
Spring
内部其实还提供有一种单线程作用域,但是这种作用域默认是没有注册到Spring
容器中的,Spring
只是提供了这种作用域的实现类。
如果想要使用,需要手动注册这种作用域:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>
<bean id="thing2" class="x.y.Thing2" scope="thread">
<property name="name" value="Rick"/>
<aop:scoped-proxy/>
</bean>
<bean id="thing1" class="x.y.Thing1">
<property name="thing2" ref="thing2"/>
</bean>
</beans>