在spring 的以前版本中,只是支持singleton,prototype两种类型,
在2.0中作了很大的改进,增加了RequestScope,和SessionScope两种范围。当然也支持自定义Scope
下面简单介绍一下,spring2.0是如何支持自定义Scope的。
Scope接口,需要实现的接口,主要的方法:
下面简单定义一个Scope对象:
如何使用让此scope生效,有两种方法:
第一编程实现:
可以使用registerScope方法来注册相应的scope
另外一种实现 xml 配置(建议使用)
通过CustomScopeConfigurer 来注册相应的Scope,由于CustomScopeConfigurer 实现了BeanFactoryPostProcessor,对于ApplcationContext,自动会实现相应的配置
当然也可以编程实现
在2.0中作了很大的改进,增加了RequestScope,和SessionScope两种范围。当然也支持自定义Scope
下面简单介绍一下,spring2.0是如何支持自定义Scope的。
Scope接口,需要实现的接口,主要的方法:
- Object get(String name, ObjectFactory objectFactory)
- Object remove(String name)
- void registerDestructionCallback(String name, Runnable callback)
下面简单定义一个Scope对象:
java 代码
new Scope() { private int index; private List objects = new LinkedList(); { objects.add(new TestBean()); objects.add(new TestBean()); } public String getConversationId() { return null; } public Object get(String name, ObjectFactory objectFactory) { if (index >= objects.size()) { index = 0; } return objects.get(index++); } public Object remove(String name) { throw new UnsupportedOperationException(); } public void registerDestructionCallback(String name, Runnable callback) { } };
Scope scope = 如何使用让此scope生效,有两种方法:
第一编程实现:
java 代码
void registerScope(String scopeName, Scope scope); String[] getRegisteredScopeNames(); Scope getRegisteredScope(String scopeName);
ConfigurableBeanFactory 定义了关于Scope的一些方法: 可以使用registerScope方法来注册相应的scope
java 代码
"myScope", scope);
applicationContext.getBeanFactory().registerScope(另外一种实现 xml 配置(建议使用)
通过CustomScopeConfigurer 来注册相应的Scope,由于CustomScopeConfigurer 实现了BeanFactoryPostProcessor,对于ApplcationContext,自动会实现相应的配置
xml 代码
<bean id="myScope" class="MyScope"/> <bean id="customerScope" class="org.springframework.beans.factory.config.CustomScopeConfigurer"> <property name="scopes"> <map> <entry key="myScope"> <bean class="myScope"/> </entry> </map> </property> </bean> <bean id="usesScope" class="org.springframework.beans.TestBean" scope="myScope"/>
当然也可以编程实现
java 代码
new HashMap(); scopes.put(this, new NoOpScope()); CustomScopeConfigurer figurer = new CustomScopeConfigurer(); figurer.setScopes(scopes);
Map scopes =