您的位置:首页 > 编程语言 > Java开发

spring自定义bean的作用域

2009-12-14 17:44 344 查看
在Spring 2.0中,Spring的bean作用域机制是可以扩展的。这意味着,你不仅可以使用Spring提供的预定义bean作用域; 还可以定义自己的作用域,甚至重新定义现有的作用域(不提倡这么做,而且你不能覆盖内置的
singleton
prototype
作用域)。

作用域由接口
org.springframework.beans.factory.config.Scope
定义。要将你自己的自定义作用域集成到Spring容器中,需要实现该接口。它本身非常简单,只有两个方法,分别用于底层存储机制获取和删除对象。自定义作用域可能超出了本参考手册的讨论范围,但你可以参考一下Spring提供的
Scope
实现,以便于去如何着手编写自己的Scope实现。

在实现一个或多个自定义
Scope
并测试通过之后,接下来就是如何让Spring容器识别你的新作用域。
ConfigurableBeanFactory
接口声明了给Spring容器注册新
Scope
的主要方法。(大部分随Spring一起发布的
BeanFactory
具体实现类都实现了该接口);该接口的主要方法如下所示:

void registerScope(String scopeName, Scope scope);

registerScope(..)
方法的第一个参数是与作用域相关的全局唯一名称;Spring容器中该名称的范例有
singleton
prototype
registerScope(..)
方法的第二个参数是你打算注册和使用的自定义
Scope
实现的一个实例。

假设你已经写好了自己的自定义
Scope
实现,并且已经将其进行了注册:

// note: the [code]ThreadScope
class does not exist; I made it up for the sake of this example
Scope customScope = new ThreadScope();
beanFactory.registerScope("thread", scope);[/code]
然后你就可以像下面这样创建与自定义
Scope
的作用域规则相吻合的bean定义了:

<bean id="..." class="..." scope="thread"/>

如果你有自己的自定义
Scope
实现,你不仅可以采用编程的方式注册自定义作用域,还可以使用
BeanFactoryPostProcessor
实现:
CustomScopeConfigurer
类,以声明的方式注册
Scope
BeanFactoryPostProcessor
接口是扩展Spring IoC容器的基本方法之一,在本章的BeanFactoryPostProcessor中将会介绍。

使用
CustomScopeConfigurer
,以声明方式注册自定义
Scope
的方法如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread" value="com.foo.ThreadScope"/>
</map>
</property>
</bean>

<bean id="bar" class="x.y.Bar" scope="thread">
<property name="name" value="Rick"/>
<aop:scoped-proxy/>
</bean>

<bean id="foo" class="x.y.Foo">
<property name="bar" ref="bar"/>
</bean>

</beans>

CustomScopeConfigurer
既允许你指定实际的
Class
实例作为entry的值,也可以指定实际的
Scope
实现类实例;详情请参见
CustomScopeConfigurer
类的JavaDoc。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: