配置方式:
<util:properties location="classpath:development.properties" id="config" />
<context:property-placeholder location="classpath*:development.properties"
ignore-unresolvable="true" ignore-resource-not-found="true"/>
< !--多个配置使用,分隔-->
1、spring 配置 util:properties和context:property-placeholder 共性:
都可以用于读取properties配置文件
2、spring 配置 util:properties和context:property-placeholder 区别:
util:properties 以实例化一个bean的方式,默认是单例类型;可以为其他bean的属性赋值,进入
java:org.springframework.beans.factory.config.PropertiesFactoryBean类中,查看一下源码:
而context:property-placeholder 是由Spring加载到上下文中,为bean的属性赋值,以${properties的key}取得值
org.springframework.context.support.PropertySourcesPlaceholderConfigurer的类中作处理;一层层代码跟下去,发现继承的类------加载properties的类是同一个。
只是需要注意的是<context:property-placeholder location=… />中需要增加,因为默认都是false,只会找一次配置,找不到就不找了,设置为true以后,找不到配置中的key,会继续找下一个,再找不到,会找系统本地JVM环境中的配置。所以要增加:
ignore-unresolvable="true" ignore-resource-not-found="true"
在 util:properties 中定义了id=“config” ,所以在使用的时候通过<context:property-placeholder properties-ref=“config”/> 加载到spring上下文中,在配置文件中就不会报一堆红色,而是把找到的值显示在配置中,方便尽早发现文件中的错误;
额外:也可以通过直接指定配置bean的方式,这样也注意要设置true;
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!– 必须添加下面这句声明 –>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:development.properties</value>
</list>
</property>
</bean>