spring自定义bean的作用域

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

作用域由接口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容器中该名称的范例有singletonprototyperegisterScope(..)方法的第二个参数是你打算注册和使用的自定义Scope实现的一个实例。

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

// note: the ThreadScope class does not exist; I made it up for the sake of this example
Scope customScope = new ThreadScope();
beanFactory.registerScope("thread", scope);

然后你就可以像下面这样创建与自定义Scope的作用域规则相吻合的bean定义了:

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

如果你有自己的自定义Scope实现,你不仅可以采用编程的方式注册自定义作用域,还可以使用BeanFactoryPostProcessor实现:CustomScopeConfigurer类,以声明的方式注册ScopeBeanFactoryPostProcessor接口是扩展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。

原文地址:https://www.cnblogs.com/liaomin416100569/p/9332064.html