Spring的PropertyPlaceholderConfigurer

在项目中我们一般将配置信息(如数据库的配置信息)配置在一个properties文件中,如下:

jdbcUrl=jdbc:mysql://localhost:3306/flowable?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE&useSSL=false&serverTimezone=UTC
userName=root
userPassword=123456
jdbcDriver=com.mysql.cj.jdbc.Driver

接着在Spring的配置文件中读取,有两种方式:

方式一:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <!-- 对于读取一个配置文件采取的方案 -->
        <property name="location" value="classpath:config.properties"></property>
        <!-- 对于读取两个以上配置文件采取的处理方案 -->
        <!--
        <property name="locations"> 
            <list>
                <value>classpath:config.properties</value>
                <value>classpath:config2.properties</value>
            </list>
        </property>
        -->
    </bean>

方式二:

<!--采用这种方式简化配置文件-->
<context:property-placeholder location="classpath:config.properties"/>

我们知道,不论是使用PropertyPlaceholderConfigurer还是通过context:property-placeholder这种方式进行实现,都需要记住,Spring框架不仅仅会读取我们的配置文件中的键值对,而且还会读取Jvm 初始化的一下系统的信息。有时候,我们需要将配置Key定一套命名规则 ,例如

项目名称.组名.功能名=配置值
org.team.tfunction=0001

同时,我们也可以使用下面这种配置方式进行配置,这里我配NEVER的意思是不读取系统配置信息。如:

<context:property-placeholder location="classpath:config.properties" system-properties-mode="NEVER"/>

测试用例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-core.xml")
public class SpringContextTest {

	@Value("${userName}")
	private String uname;

	@Value("${userPassword}")
	private String pwd;

	@Test
	public void test() {
		System.out.println("username:" + uname);
		System.out.println("password:" + pwd);
	}

}
username:root
password:123456

配置文件中使用就比较简单了:

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<!-- 数据库基本信息配置 -->
		<property name="url"
			value="${jdbcUrl}" />
		<property name="username" value="${userName}" />
		<property name="password" value="${userPassword}" />
		<property name="driverClassName" value="${jdbcDriver}" />
</bean>
原文地址:https://www.cnblogs.com/foxting/p/8488441.html