Spring中两种常用的容器后处理器

我与影子孤独终老i 提交于 2019-12-05 03:49:44

    容器后处理器是一种特殊的Bean,这种Bean并不对外提供服务,它甚至可以无需id属性,它主要负责对容器本身进行某些特殊的处理。

PropertyPlaceholderConfigurer后处理器

    PropertyPlaceholderConfigurer是Spring提供的一个容器后处理器,负责读取properties属性文件里的属性值,并将这些属性值设置成Spring配置文件的元数据。通过使用PropertyPlaceholderConfigurer,可以将Spring配置文件中的部分元数据放在属性文件中设置,这种配置方式当然有其优势:可以将部分相似的配置(比如数据库的URL,用户名和密码等)放在特定的属性文件中,如果只需要修改这部分配置,则无需修改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。

    注意:如果使用以下方式使用容器,是不需要为PropertyPlaceholderConfigurer配置id,也不需要手动为容器注册这个后处理器,因为ApplicationContext可自动检测到容器中的后处理器,并自动注册:

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

    本例用到的属性文件dp.properties内容如下:

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

PropertyOverrideConfigurer后处理器

    PropertyOverrideConfigurer是Spring提供的另一个容器后处理器,这个后处理器的作用比上面那个后处理器更加强大:PropertyOverrideConfigurer的属性文件指定的信息可以直接覆盖Spring配置文件中的元数据,看例子:

<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时,这些值就可以被后处理器读取后覆盖原来的空值,否则程序将出错。属性文件的内容如下:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!