单例模式解析properties 配置文件

配置文件

dbURL=jdbc:oracle:thin:@10.0.19.252:1521:orcl
dbDriver=oracle.jdbc.driver.OracleDriver
username=moto
password=123456

解析

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class DbInfo {

    private static DbInfo dbInfo; //static修饰 只初始化一次
    private String dbDriver;
    private String dbURL;
    private String username;
    private String password;
    private DbInfo(){}

    public static DbInfo instance() throws Exception{
        if(dbInfo == null){
            dbInfo = new DbInfo();
            dbInfo.init();
        }
        return dbInfo;
    }

    private void init() throws Exception{
        Properties prop = new Properties();
        String path = DbInfo.class.getResource("/").getPath() + "db.properties"; // 使用反射 获取文件绝对路径以'/'开始
        prop.load(new FileInputStream(new File(path)));
        this.dbDriver = prop.getProperty("dbDriver");
        this.dbURL = prop.getProperty("dbURL");
        this.username = prop.getProperty("username");
        this.password = prop.getProperty("password");
    }

    public String getDbDriver() {
        return dbDriver;
    }

    public String getDbURL() {
        return dbURL;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }
}

测试

import com.icss.util.DbInfo;

public class Test {

    public static void main(String[] args) {
        try {
            DbInfo dbInfo = DbInfo.instance();
            System.out.println(dbInfo.getDbDriver());
            System.out.println(dbInfo.getDbURL());
            System.out.println(dbInfo.getUsername());
            System.out.println(dbInfo.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值