[Spring] Bean的作用域Scope

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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值