spring2.0 自定义Scope

在spring 的以前版本中,只是支持singleton,prototype两种类型,
在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)
get 和remove这是最常用的方法,registerDestructionCallback用于回收对象时,可以异步调用其它操作。
下面简单定义一个Scope对象:
 
Scope scope = 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生效,有两种方法:
第一编程实现:
ConfigurableBeanFactory 定义了关于Scope的一些方法:
void registerScope(String scopeName, Scope scope);
String[] getRegisteredScopeNames();
Scope getRegisteredScope(String scopeName);
可以使用registerScope方法来注册相应的scope
 
applicationContext.getBeanFactory().registerScope("myScope", scope);     

另外一种实现 xml 配置(建议使用)
  通过CustomScopeConfigurer 来注册相应的Scope,由于CustomScopeConfigurer 实现了BeanFactoryPostProcessor,对于ApplcationContext,自动会实现相应的配置
 
<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"/>     

当然也可以编程实现
 
Map scopes = new HashMap();
scopes.put(this, new NoOpScope());                        
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);     


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值