Bean的作用域
Spring Framework支持五种作用域(其中有三种只能用在基于web的Spring
ApplicationContext
)。
作用域 | 描述 |
---|---|
singleton |
在每个Spring IoC容器中一个bean定义对应一个对象实例。 |
prototype |
一个bean定义对应多个对象实例。 |
request |
在一次HTTP请求中,一个bean定义对应一个实例;即每次HTTP请求将会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring |
session |
在一个HTTP |
global session |
在一个全局的HTTP |
一、singleton作用域
<bean id="role" class="spring.chapter2.maryGame.Role"scope="singleton"/>
或者
<bean id="role" class="spring.chapter2.maryGame.Role"singleton="true"/>
二、prototype
getBean()
方法)都会产生一个新的bean实例,相当与一个new的操作,对于prototype作用域的bean,有一点非常重要,那就是Spring不能对一个prototype bean的整个生命周期负责,容器在初始化、配置、装饰或者是装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例不闻不问了。不管何种作用域,容器都会调用所有对象的初始化生命周期回调方法,而对prototype而言,任何配置好的析构生命周期回调方法都将不会被调用。清除prototype作用域的对象并释放任何prototype
bean所持有的昂贵资源,都是客户端代码的职责。(让Spring容器释放被singleton作用域bean占用资源的一种可行方式是,通过使用bean的后置处理器,该处理器持有要被清除的bean的引用。)<bean id="role" class="spring.chapter2.maryGame.Role" scope="prototype"/>
或者
<bean id="role" class="spring.chapter2.maryGame.Role" singleton="false"/>
三、request
<web-app>
...
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
...
</web-app>
<web-app>
..
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
<bean id="role" class="spring.chapter2.maryGame.Role" scope="request"/>
四、session
<bean id="role" class="spring.chapter2.maryGame.Role" scope="session"/>
五、global session
<bean id="role" class="spring.chapter2.maryGame.Role" scope="global session"/>
六、自定义bean装配作用域
publicclass MyScope implements Scope {
private final ThreadLocal threadScope = new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
}
};
public Object get(String name, ObjectFactory objectFactory) {
Map scope = (Map) threadScope.get();
Object object = scope.get(name);
if(object==null) {
object = objectFactory.getObject();
scope.put(name, object);
}
return object;
}
public Object remove(String name) {
Map scope = (Map) threadScope.get();
return scope.remove(name);
}
publicvoid registerDestructionCallback(String name, Runnable callback) {
}
public String getConversationId() {
// TODO Auto-generated method stub
returnnull;
}
}