gpt4 book ai didi

java - 如何使变量/常量初始化后始终可用?

转载 作者:行者123 更新时间:2023-12-01 16:36:11 26 4
gpt4 key购买 nike

我有一个 swing 应用程序,必须连接到数据库才能获取某些资源,为此我使用 .properties 文件来存储数据库属性,并且可以在运行时读取该属性。
为此,我使用以下代码

    public void readPropertiesFile(){
try{
InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
Properties prop = new Properties();
prop.load(is);
String URL = prop.getProperty("DB_URL");
String user = prop.getProperty("DB_USER");
String pwd = prop.getProperty("DB_PWD");
is.close();
/* code to use values read from the file*/
}catch(Exception e){
System.out.println("Failed to read from " + PROP_FILE + " file.");
}
}

但每当我想连接到数据库时我都必须调用此方法(对于 Connection 对象)。我知道现在处理速度足够快,可以在微秒内运行这些行,但据我自己的知识,建议我在应用程序启动或用户第一次尝试连接到数据库时存储这些数据库值的方法对于此类对象变量常量中的任何操作,这些操作在应用程序重新启动之前都可用,并且可以直接调用而无需读取文件。

附注:我知道数据库值不会经常更改,如果发生这种情况,我会很乐意重新启动我的应用程序:)

最佳答案

通过将这些静态字段放在单独的类中,只有在您第一次访问 URL、USER 或 PASSWORD 时才会加载它们。

public class DbProps {
public static final String URL;
public static final String USER;
public static final String PASSWORD;

static {
try{
InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
try {
Properties prop = new Properties();
prop.load(is);
URL = prop.getProperty("DB_URL");
USER = prop.getProperty("DB_USER");
PASSWORD = prop.getProperty("DB_PWD");
} finally {
is.close();
}
}catch(Exception e){
throw new RuntimeException("Failed to read from " + PROP_FILE + " file.", e);
}
}
}

关于java - 如何使变量/常量初始化后始终可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8744104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com