Spring中兩種經常使用的容器後處理器

    容器後處理器是一種特殊的Bean,這種Bean並不對外提供服務,它甚至能夠無需id屬性,它主要負責對容器自己進行某些特殊的處理。java

PropertyPlaceholderConfigurer後處理器mysql

    PropertyPlaceholderConfigurer是Spring提供的一個容器後處理器,負責讀取properties屬性文件裏的屬性值,並將這些屬性值設置成Spring配置文件的元數據。經過使用PropertyPlaceholderConfigurer,能夠將Spring配置文件中的部分元數據放在屬性文件中設置,這種配置方式固然有其優點:能夠將部分類似的配置(好比數據庫的URL,用戶名和密碼等)放在特定的屬性文件中,若是隻須要修改這部分配置,則無需修改Spring配置文件。例如:spring

<bean class="org.springframework.beans.factory.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <!-- 若是有多個屬性文件,一併列在這裏 -->
            <value>db.properties</value>
            <!-- <value>xxx.properties</value> -->
        </list>
    </property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <!-- 如下這些值均來自配置文件dp.properties -->
    <property name="driverClass" value="${jdbc.driverClass}" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="user" value="${jdbc.user}" />
    <property name="password" vaue="${jdbc.password}" />
</bean>
<!--
    other beans' definition
-->

    在上面的配置文件中,dataSouce的幾個鏈接屬性的value都來自屬性文件中,這代表Spring容器將從propertyConfigurer指定屬性文件中搜索這些key對應的value,併爲對應的Bean屬性設置這些value。
sql

    注意:若是使用如下方式使用容器,是不須要爲PropertyPlaceholderConfigurer配置id,也不須要手動爲容器註冊這個後處理器,由於ApplicationContext可自動檢測到容器中的後處理器,並自動註冊:
數據庫

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
context.getBean("xxx");

    本例用到的屬性文件dp.properties內容以下:
ide

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb
jdbc.user=root
jdbc.password=123456

PropertyOverrideConfigurer後處理器
url

    PropertyOverrideConfigurer是Spring提供的另外一個容器後處理器,這個後處理器的做用比上面那個後處理器更增強大:PropertyOverrideConfigurer的屬性文件指定的信息能夠直接覆蓋Spring配置文件中的元數據,看例子:spa

<bean class="org.springframework.beans.factory.PropertyOverrideConfigurer">
    <property name="locations">
        <list>
            <!-- 若是有多個屬性文件,一併列在這裏 -->
            <value>db.properties</value>
            <!-- <value>xxx.properties</value> -->
        </list>
    </property>
</bean>
<!-- 這個dataSource沒有指定屬性值,但properties文件中的數據將會直接覆蓋dataSource中的值 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" />
<!--
    other beans' definition
-->

    上面的dataSource沒有指定任何信息,可是由於Spring容器中部署了一個PropertyOverrideConfigurer的容器後處理器,並且Spring使用ApplicationContext做爲容器,它將自動檢測容器中的後處理器並自動註冊。PropertyOverrideConfigurer讀取db.properties文件中的屬性後,找到beans.xml文件中匹配的屬性,並將其值替換掉。所以只要db.properties中的屬性的定義格式爲:dataSource.propertyName=value時,這些值就能夠被後處理器讀取後覆蓋原來的空值,不然程序將出錯。屬性文件的內容以下:code

dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/testdb
dataSource.user=root
dataSource.password=123456
相關文章
相關標籤/搜索