Spring4.X之Bean的Scope


https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Bean scopes


1、singleton
默认范围。
        一个 Spring IoC 容器中只有一个 bean.
        注意:这与单例设计模式不是一个概念。

用法:
<bean id="s" class="x.x.XService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -->
<bean id="s" class="x.x.XService" scope="singleton"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="s" class="x.x.XService" singleton="true"/>



2、prototype
        原型模式:
        就像是使用 Java 类一样,可以产生任意多个bean的实例。
       

用法:
<!-- using spring-beans-2.0.dtd -->
<bean id="s" class="x.x.XService" scope="prototype"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="s" class="x.x.XService" singleton="false"/>




下面三种只在 Web 容器中可用

1、request
Scopes a single bean definition to the life cycle of a single HTTP request;
that is each and every HTTP request will have its own instance of a bean created
off the back of a single bean definition.
- Only valid in the context of a web-aware Spring ApplicationContext.

用法:
<bean id="s" class="x.x.XService" scope="request"/>



2、session
Scopes a single bean definition to the life cycle of a HTTP Session.
- Only valid in the context of a web-aware Spring ApplicationContext.
用法:
<bean id="s" class="x.x.XService" scope="session"/>




3、global session
Scopes a single bean definition to the life cycle of a global HTTP Session.
Typically only valid when used in a port-let context.
- Only valid in the context of a web-aware Spring ApplicationContext.

用法:
<bean id="s" class="x.x.XService" scope="globalSession"/>

















-

猜你喜欢

转载自lixh1986.iteye.com/blog/2398815