工程管理之一:配置文件工具类

在各个项目中,总会用到各种数据库连接或连接池等基础信息。如果使用常量写在程序里,恐怕不利于修改配置和部署。这里总结一个在工作中常用的配置文件的工具类。

由于这个类主要读取的是数据库配置,因此类名为DatabaseProject,当然读取不同配置也可以使用其他类名。

public final class DatabaseProject {

	public static final Logger LOGGER = LoggerFactory.getLogger(DatabaseProject.class);
	
	//You must call init() before really use DB.
	public static CompositeConfiguration DB_CONFIG = new CompositeConfiguration();
	
	public static void init(String confDir)
	{
		DB_CONFIG = getConfiguration(confDir,"db.properties");
	}
	
	public static CompositeConfiguration getConfiguration(String confDir,
                                                          String prop) {
        CompositeConfiguration config = new CompositeConfiguration();
        File file = new File(confDir + "/" + prop);
        FileChangedReloadingStrategy reloadingStrategy = new FileChangedReloadingStrategy();
        reloadingStrategy.setRefreshDelay(10000);// 10s
        URL url = null;
        try {
            if (file.exists()) {
                url = file.toURI().toURL();
            } else {
                url = org.apache.commons.configuration.ConfigurationUtils
                        .locate(prop);
            }
            LOGGER.info("loading conf from:" + url);
            PropertiesConfiguration fileConfiguraton = new PropertiesConfiguration();
            fileConfiguraton.load(url);
            fileConfiguraton.setReloadingStrategy(reloadingStrategy);
            config.addConfiguration(fileConfiguraton);
        } catch (Exception e) {
            LOGGER.error("Failed to load config:" + prop, e);
        }
        return config;
    }

	public static void main(String[] args){
		DatabaseProject.init("src");
	}
}

这个类中主要使用了apache的commons-configuration包,日志使用slf4j、logback等jar包。

主要方法是getConfiguration,获取properties文件配置路径和文件名,并启用FileChangedReloadingStrategy文件修改后重新加载策略,返回CompositeConfiguration实例。

使用方法:

DatabaseProject.init("src");//初始化传入配置文件路径
//
DatabaseProject.DB_CONFIG.containsKey("mongodb.ips")
DatabaseProject.DB_CONFIG.getString("mongodb.ip");
DatabaseProject.DB_CONFIG.getInt("mongodb.port");

 以上就是这个工具类简单的使用介绍,commons-configuration包还提供了有不少工具,大家后续可以查看API文档再慢慢完善这个类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值