一般的spring框架都是用在web项目中,xml中的properties文件的配置一般都是classpath:db.properties的格式。
但在非web项目中,需要将这些db.propperties文件独立放在一个conf文件夹中,那么就无法使用classpath:这种格式了。
方法如下:
<bean id="configBean"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>file:${collectiongaode.dir}/conf/db.properties</value>
</property>
</bean>
file后面的参数collectiongaode.dir java的环境变量,可以在java -Dcollectongaode.dir=/root 来指定,也可以在程序中 System.setproperty(keyt,value)的方法设置。
这样做的好处就是可以像tomcat一样,lib文件夹放jar包,conf文件夹放db.properties配置文件,bin下放启动文件 start.sh
PRG="$0"
while [ -h "$PRG" ]; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`/"$link"
fi
done
# Get standard environment variables
PRGDIR=`dirname "$PRG"`
# Only set CATALINA_HOME if not already set
[ -z "$GAODE_HOME" ] && GAODE_HOME=`cd "$PRGDIR/.." >/dev/null; pwd`
echo GAODE_HOME
echo $GAODE_HOME
java -Dcollectiongaode.dir=$GAODE_HOME -jar $GAODE_HOME/lib/gaode.jar
这样做的好处就是可以将一个jar项目做成产品化的形式,否则配置文件放在jar包中,每次修改配置都需要重新修改jar包。
这里还有一点,在读取springContext.xml配置文件中,一定要在路径前添加file:协议
private static ApplicationContext ctx = new FileSystemXmlApplicationContext(
"file:" + System.getProperty("collectiongaode.dir")
+ File.separator + "conf" + File.separator
+ "applicationContext.xml");
不添加file:协议在windows下没问题,但是在linux下,会重复collectiongaode.dir 路径 如下
2017-04-19 00:07:45.815, [main ], [INFO ], XmlBeanDefinitionReader.loadBeanDefinitions(315), | Load
ing XML bean definitions from URL [file:/root/collectiongaode/root/collectiongaode/conf/applicationContext.xml]