2008年(60)
分类: Java
2008-08-02 22:35:29
getBean()方法)都会产生一个新的bean实例,相当与一个new的操作,对于prototype作用域的bean,有一点非常重要,那就是Spring不能对一个prototype bean的整个生命周期负责,容器在初始化、配置、装饰或者是装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例不闻不问了。不管何种作用域,容器都会调用所有对象的初始化生命周期回调方法,而对prototype而言,任何配置好的析构生命周期回调方法都将不会被调用。清除prototype作用域的对象并释放任何prototype bean所持有的昂贵资源,都是客户端代码的职责。(让Spring容器释放被singleton作用域bean占用资源的一种可行方式是,通过使用bean的后置处理器,该处理器持有要被清除的bean的引用。)
<web-app>
...
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListenerlistener-class>
listener>
...
web-app>
<web-app>
..
<filter>
<filter-name>requestContextFilterfilter-name>
<filter-class>org.springframework.web.filter.RequestContextFilterfilter-class>
filter>
<filter-mapping>
<filter-name>requestContextFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
...
web-app>

publicclass MyScope implements Scope ...{ 
privatefinal ThreadLocal threadScope = new ThreadLocal() ...{
protected Object initialValue() ...{
returnnew 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;
}
}