在2.0中作了很大的改進(jìn),增加了RequestScope,和SessionScope兩種范圍。當(dāng)然也支持自定義Scope
下面簡(jiǎn)單介紹一下,spring2.0是如何支持自定義Scope的。
Scope接口,需要實(shí)現(xiàn)的接口,主要的方法:
- Object get(String name, ObjectFactory objectFactory)
- Object remove(String name)
- void registerDestructionCallback(String name, Runnable callback)
下面簡(jiǎn)單定義一個(gè)Scope對(duì)象:
?
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生效,有兩種方法:
第一編程實(shí)現(xiàn):
ConfigurableBeanFactory 定義了關(guān)于Scope的一些方法:
void registerScope(String scopeName, Scope scope);
String[] getRegisteredScopeNames();
Scope getRegisteredScope(String scopeName);
可以使用registerScope方法來注冊(cè)相應(yīng)的scope
?
applicationContext.getBeanFactory().registerScope("myScope", scope);??? ?
另外一種實(shí)現(xiàn) xml 配置(建議使用)
? 通過CustomScopeConfigurer 來注冊(cè)相應(yīng)的Scope,由于CustomScopeConfigurer 實(shí)現(xiàn)了BeanFactoryPostProcessor,對(duì)于ApplcationContext,自動(dòng)會(huì)實(shí)現(xiàn)相應(yīng)的配置
?
<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"/>??? ?
當(dāng)然也可以編程實(shí)現(xiàn)
?
Map scopes = new HashMap();
scopes.put(this, new NoOpScope()); ??? ??? ??? ??? ??? ???
CustomScopeConfigurer figurer = new CustomScopeConfigurer();
figurer.setScopes(scopes);??? ?