`
sundful
  • 浏览: 1231358 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

关于系统读取properties配置文件的路径问题,包括打成jar包的运行文件

    博客分类:
  • Java
 
阅读更多

在当前的一个项目中,遇到以下业务需要:

1.开发环境是在myeclipse里运行的时候,启动服务后,有一个加载配置文件属性信息的Global.java。用于得到配置文件里的配置信息;

2.发布系统的时候,需要把系统打成jar执行,这时候之前的加载配置文件的方法就不起作用了得不到配置文件的路径;

3.因在系统刚启动时,需要启动加载一个Listener,在Listener里又加载了一个配置文件。

4.以上加载配置文件,都是只能加载一次配置文件,当配置文件的内容修改后,只能再次重启服务后才能读取到变动的配置内容,系统中有些配置参数是需要时时获取配置文件里的最新参数信息。

如何在以上场景加载配置文件呢,通过来回的找资料、调试,终于搞定。以下是具体代码:

package test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
public class Test {
	public static void main(String[] args) throws Exception{
		System.out.println(load1());//通过ClassLoader方式加载配置文件
		System.out.println(load2());//
		
	}
	/**
	 * 通过ClassLoader方式加载配置文件
	 * 这种加载方式:
	 * 			1.可在myeclipse里运行时得到配置文件路径;
	 * 			2.亦可在把项目打成jar包运行时,得到配置文件路径;
	 */
	public static String load1()throws Exception{
		Properties p = new Properties();
		InputStream in = Test.class.getClassLoader().getResourceAsStream("config/config.properties");
		p.load(in);
		return  p.getProperty("user_name").toString().trim(); 
	}
	
	/**
	 * 自动加载配置文件机制,可在修改配置文件后,不用重启服务也能得到配置文件的新内容
	 */
	public static String load2()throws Exception{
		String file_name = Test.class.getClassLoader().getResource("config/config.properties").getFile();
		Properties p = new Properties();
		PropertiesConfiguration propconfig =null;//创建自动加载的机制
		propconfig = new PropertiesConfiguration();
		propconfig.setEncoding("UTF-8");//设置编码
		propconfig.setReloadingStrategy(new FileChangedReloadingStrategy());//设置自动冲加载机制
		p.load(new FileInputStream(file_name));
		return p.getProperty("user_name").toString().trim();//每次调用这个方法都会从配置文件里取到最新的参数
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics