单例模式解析properties 配置文件

电玩女神 2022-06-07 00:52 236阅读 0赞

配置文件

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

解析

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.util.Properties;
  4. public class DbInfo {
  5. private static DbInfo dbInfo; //static修饰 只初始化一次
  6. private String dbDriver;
  7. private String dbURL;
  8. private String username;
  9. private String password;
  10. private DbInfo(){}
  11. public static DbInfo instance() throws Exception{
  12. if(dbInfo == null){
  13. dbInfo = new DbInfo();
  14. dbInfo.init();
  15. }
  16. return dbInfo;
  17. }
  18. private void init() throws Exception{
  19. Properties prop = new Properties();
  20. String path = DbInfo.class.getResource("/").getPath() + "db.properties"; // 使用反射 获取文件绝对路径以'/'开始
  21. prop.load(new FileInputStream(new File(path)));
  22. this.dbDriver = prop.getProperty("dbDriver");
  23. this.dbURL = prop.getProperty("dbURL");
  24. this.username = prop.getProperty("username");
  25. this.password = prop.getProperty("password");
  26. }
  27. public String getDbDriver() {
  28. return dbDriver;
  29. }
  30. public String getDbURL() {
  31. return dbURL;
  32. }
  33. public String getUsername() {
  34. return username;
  35. }
  36. public String getPassword() {
  37. return password;
  38. }
  39. }

测试

  1. import com.icss.util.DbInfo;
  2. public class Test {
  3. public static void main(String[] args) {
  4. try {
  5. DbInfo dbInfo = DbInfo.instance();
  6. System.out.println(dbInfo.getDbDriver());
  7. System.out.println(dbInfo.getDbURL());
  8. System.out.println(dbInfo.getUsername());
  9. System.out.println(dbInfo.getPassword());
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. }

发表评论

表情:
评论列表 (有 0 条评论,236人围观)

还没有评论,来说两句吧...

相关阅读