一、屬性文件加載
方案1:通配符解決、逗號(hào)分隔
使用通配符讓spring一次性讀取多個(gè)屬性文件到一個(gè)PropertyPlaceholderConfigurerbean中
<context:property-placeholder location="classpath:conf/.properties"/>
或者使用
<context:property-placeholder location="classpath*:conf/db.properties,conf/sys.properties"/>
注意: 如果后一個(gè)文件中有和前面某一個(gè)文件中屬性名是相同的,最終取的值是后加載的值
方案2:一個(gè)PropertySourcesPlaceholderConfigurer中包含多個(gè)屬性文件,和方案1原理相同
<bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
<value>classpath:sys.properties</value>
</list>
</property>
方案3:使用ignore-unresolvable
如果一定要分開(kāi)定義,則在每個(gè)PropertySourcesPlaceholderConfigurer配置中添加
<property name="ignoreUnresolvablePlaceholders" value="true"/>
或者在每個(gè)context:property-placeholder中都加上ignore-unresolvable="true"
因?yàn)樵谀闶褂聾Value("${xx}")或在xml中使用${xx}獲取屬性時(shí),Spring會(huì)在第一個(gè)讀取到的屬性文件中去找,如果沒(méi)有就直接拋出異常,而不會(huì)繼續(xù)去第二個(gè)屬性文件中找。
二、屬性獲取
方案一:Bean中直接注入Properties配置文件中的值
<bean id="settings"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>file:/opt/rms/config/rms-mq.properties</value>
<value>file:/opt/rms/config/rms-env.properties</value>
</list>
</property>
</bean>
Client類中使用Annotation如下:
import org.springframework.beans.factory.annotation.Value;
public
class Client() {
@Value("#{remoteSettings['remote.ip']}")
private String ip;
@Value("#{remoteSettings['remote.port']}")
private String port;
@Value("#{remoteSettings['remote.serviceName']}")
private String service;
}
注意:被注入屬性的那個(gè)類,如果被其他類作為對(duì)象引用(被調(diào)用)。這個(gè)被調(diào)用的類也必須選擇注解的方式,注入到調(diào)用他的那個(gè)類中,不能用 new出來(lái)做對(duì)象,new出來(lái)的對(duì)象再注入其他bean就會(huì)發(fā)生屬性獲取不到的現(xiàn)象。所以要被調(diào)用的javabean,都需要@service,交給Spring去管理才可以,這樣他就默認(rèn)注入了。