前段时间作了一个项目,在开发的过程当中,也没有考虑到配置文件的问题。后来项目完成了,打包的时候要求,要求将项目中的配置文件外移,方便修改配置文件。花了我两天多的时间 java
才弄明白,因而记录下,以防之后再遇到相似问题。 spring
使用spring的org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类加载Properties配置文件,经过源码能够知道,默认加载的是classpath下的文件,配 shell
置以下: spa
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:config/init.properties</value> </property> </bean>
若是有多个配置文件加载,则: code
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config/init.properties</value> <value>classpath:config/init.properties</value> </list> </property> </bean>
这样spring就可以加载properties文件了。 blog
可是对于外部目录的配置文件,使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer也是能够加载的,不过要修改他的路径配置方式,以下: 开发
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>file:${user.dir}/config/init.properties</value> <value>file:${user.dir}/config/init2.properties</value> </list> </property> </bean>
这样就能够成功加载外部目录的配置文件了,${user.dir}是系统变量,指用户当前目录所在。 get
应该某些需求,配置文件得从java代码是加载,这里我就说同样代码中加载外部目录的配置文件的方式,加载classpath目录下的配置文件这里就再也不多说了,相信 源码
网上有太多较好的简答。以下代码: 博客
private static final Properties sysConfig = new Properties(); static { try { InputStream iStream = new FileInputStream(new File("config", "shellConfig.properties")); sysConfig.load(iStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static String getPropertyValue(String key){ return sysConfig.getProperty(key); }
但愿对你们有所帮助!