在spring中經常將常用的屬性放在properties文件中,然後再spring的配置文件中使用PropertyPlaceholderConfigurer引用properties文件。
對於web項目來說,可以通過相對路徑得到配置文件的路徑,而對於可執行項目,在團隊開發中就需要根據各自的環境來指定properties配置文件的路徑了。
對於這種情況可以將配置文件的路徑放在java虛擬機JVM的自定義變量中,例如:-Dconfig.path=/yourpath/1.properties
如下在配置文件中使用$config.path
來引用JVM自定義變量的值就可以了:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>$config.path</value> </property> </bean> <bean id="helloBean" class="onlyfun.caterpillar.HelloBean"> <property name="helloWord"> <value>${onlyfun.caterpillar.helloWord}</value> </property> </bean>