两种方式实现加载配置文件 - java代码模板

单例模式:

public class ConfigManager {
    private static ConfigManager configManager = null;
    private Properties properties = new Properties();

    private ConfigManager() {
        try {
            properties.load(new FileInputStream("src/data.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ConfigManager newInstance() {
        if (configManager == null) {
            configManager = new ConfigManager();
        }
        return configManager;
    }

    public String getValue(String key) {
        return properties.get(key).toString();
    }
}

静态代码块方式:

public class ConfigManager1 {
    private static String name = null;
    private static String pwd = null;
    private static String driver = null;
    private static String url = null;

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src/data.properties"));
            name = properties.getProperty("name");
            pwd = properties.getProperty("pwd");
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getName() {
        return name;
    }

    public static String getPwd() {
        return pwd;
    }

    public static String getDriver() {
        return driver;
    }

    public static String getUrl() {
        return url;
    }
}

你可能感兴趣的:(两种方式实现加载配置文件 - java代码模板)