如何使变量/常量初始化后始终可用?
我有一个 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
对象)时,我都必须调用此方法。 我知道现在处理速度足够快,可以在微秒内运行这些行,但据我自己的知识,建议我在应用程序启动或用户第一次尝试连接到数据库时存储这些数据库值的方法对于此类对象
或变量
或常量
中的任何操作,这些操作在应用程序重新启动之前都可用,并且可以直接调用而无需读取文件。
PS:我知道数据库值不会经常改变,如果发生这种情况,我会很乐意重新启动我的应用程序:)
I've a swing application that has to connect to database for some resources, for this i used .properties
file to store database properties and that can be read at runtime.
For this i am using the following code
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.");
}
}
but i've to call this method whenever i want to connect to the database (for Connection
object).
I know the thing that now processing is fast enough to run these lines in micro seconds, but it's for my own knowledge that suggest me the ways through which i can store these DB values when application starts or the first time user try to connect to DB for any operation in such objects
or variables
or constants
that will be usable until the application restarts and can be called directly without reading the file.
P.S. : I know that the DB values will not change oftentimes, and if it happens than i'll be happy to restart my application :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过将这些静态字段放在单独的类中,直到您第一次访问 URL、USER 或 PASSWORD 时才会加载它们。
by making these static fields in a separate class, they will not be loaded until the first time you access URL,USER, or PASSWORD.
您可以取消检查条件,该条件将检查是否是第一次,然后设置该值,否则使用现有值
You can nake a check condition which will check if it is first time then set the value other wise use the existing value
这是适合您的通用环境类。您可以获取数据库道具,例如
Environment.getEnvironment().getProperty("DB_URL")
等。Here's a generic environment class for you. You can get your DB props like
Environment.getEnvironment().getProperty("DB_URL")
, etc.