Spring——PropertyPlaceholderConfigurer详解

发布时间:2023-05-19

一、作用及概述

PropertyPlaceholderConfigurer用于解决Spring配置文件中的配置项之间的依赖关系,动态地替换占位符为实际的属性值,其最主要的作用有两个:

  1. 将属性文件中的属性值进行提取,方便Spring的使用和管理。
  2. 在大型的系统中,经常会有很多配置文件,可能一个主配置文件还会引用一些子配置文件,使用PropertyPlaceholderConfigurer显然会方便很多。

二、属性介绍

PropertyPlaceholderConfigurer包括以下三个属性:

  1. location:属性文件的路径,可以是绝对路径,也可以是相对路径;
  2. fileEncoding:指定属性文件的编码格式,默认是ISO8859-1;
  3. ignoreUnresolvablePlaceholders:是否忽略未解析的占位符,默认为false。
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:config.properties" />
</bean>

三、使用方法

  1. 通过一个propertyConfigurer替换配置文件中的属性值。 以配置文件config.properties为例,其内容如下:
# config.properties
db.url=jdbc:mysql://localhost:3306/test
db.driver=com.mysql.jdbc.Driver
db.username=root
db.password=123456

对应的Spring配置如下:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>${db.driver}</value>
    </property>
    <property name="url">
        <value>${db.url}</value>
    </property>
    <property name="username">
        <value>${db.username}</value>
    </property>
    <property name="password">
        <value>${db.password}</value>
    </property>
</bean>
  1. 在Spring的XML配置文件中通过${}给出占位符,然后在配置文件中指定具体的属性值。 示例代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="pet" class="com.test.Pet">
        <property name="name" value="${pet.name}" />
        <property name="type" value="${pet.type}" />
    </bean>
    <!-- 引入属性文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:pet.properties" />
    </bean>
</beans>

四、小结

PropertyPlaceholderConfigurer主要用于解决Spring配置文件中的依赖关系问题,其主要的作用有两个:将属性文件中的属性值进行提取,方便Spring的使用和管理;在大型的系统中,经常会有很多配置文件,可能一个主配置文件还会引用一些子配置文件,使用PropertyPlaceholderConfigurer显然会方便很多。 通过指定属性文件的路径,以及使用${}占位符指明具体的属性值,PropertyPlaceholderConfigurer可以让配置更加灵活,也更加易于管理。对于一个Java开发人员来说,熟练掌握PropertyPlaceholderConfigurer的使用,至关重要。