工作记录之Spring学习笔记(3)Bean作用域

来源:互联网 发布:尘埃3 mac g29设置 编辑:程序博客网 时间:2024/06/07 09:09

写在前面

Spring 的作用域有一些复杂,在这里记录一下,加深下印象;哈哈哈;

Spring的作用域

Spring的作用域分别有一下几个:singleton ,prototype ,request ,session ,global session;

singleton: 就是这个Bean自始自终都只有一份,和设计模式中单例设计模式差不多。
prototype: 这个就是和上面的单例设计模式完全相反的一种作用域,这种Bean在每次被使用时都会被创建一份。
request :在请求中才会创建它们的实例。
session :这个自然是创建在会话中的实例。

对于singleton ,prototype作用域到没有什么说的,但是对于request ,session ,global session,如果他们是作为其他类的成员时,那么在配置这些Bean时,必须使用代理的方式。

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">          <!-- this next element effects the proxying of the surrounding bean -->                    <aop:scoped-proxy/>    </bean>

想想其实也很简单,如果你是请求生成的对象,请求完毕就没有了,还怎么去作为其他类的依赖。

另外Bean也是可以继承的,和面向对象中的继承没有任何区别,父类可以不用写class属性。例如:

// 官方文档的例子<bean id="inheritedTestBeanWithoutClass" abstract="true">    <property name="name" value="parent"/>    <property name="age" value="1"/></bean><bean id="inheritsWithClass" class="org.springframework.beans.DerivedTestBean"    parent="inheritedTestBeanWithoutClass" init-method="initialize">  <property name="name" value="override"/>  <!-- age will inherit the value of 1 from the parent bean definition--></bean>
0 0