Spring 中 用 ${xxx} 读取properties文件的说明

properties 如果在 spring 中通过 PropertyPlaceholderConfigurer 加载,当spring 中需要 用到 properties 中的一些 key 和value 值时可以 利用 PorpertyPlaceholderConfiger 提供的$ 直接 取得。

PorpertyPlaceholderConfiger 有一些常用的属性,在一些高级应用中,可能会用到

  • locations 
  • fileEncoding 属性文件的编码格式
  • order 文件中定义了多个PropertyPlaceholderConfigurer,则通过该属性指定优先顺序。
  • placeholderPrefix 默认前缀占位符是"${"。可以根据需要改为其它的前缀符。  --- 这个特点估计就是 spring 中能用${xxx} 取得 properties 文件中的内容的理由吧,即估计是spring只要看到 是 ${  占位符 就会 到 PropertyPlaceholderConfigurer 中去找其加载的 properties文件,从而 spring能用${}取得 properties 中属性值。
  • placeholdersuffix 默认后缀占位符是“}”。
  • 由于 PropertyPlaceholderConfigurer内置的功能非常丰富,如果它未找到${xxx}中定义的xxx键,它还会去JVM系统属性(System.getProperty())和环境变量(System.getenv())中寻找。通过启用systemPropertiesMode和searchSystemEnvironment属性,开发者能够控制这一行为。
  • ${} 还可以直接用在 java bean 上即用在类上,详见:http://www.cnblogs.com/wzhanke/p/4838890.html

举例如下:

<bean

class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:*.properties</value>
</list>
</property>
</bean>
 
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  <property name="driverClass" value="${driverClass}"></property>   --->表明 properties文件中有 driverClass = aaa,通过${driverClass} 就能拿到 aaa值了
  <property name="jdbcUrl" value="${url}"></property>
</bean>
 
 
原文地址:https://www.cnblogs.com/wzhanke/p/4839004.html