java中属于常量_java中的常量和属性

Java最佳实践建议将属性作为常量读取.那么,您认为达到目标的最佳方法是什么?我的方法是:一个Configuration类只读取一次属性文件(单例模式),并使用此类在需要时读取属性作为常量.并存储一个Constants类:

>属性名称可在属性文件中找到它们(例如app.database.url).

>静态常量(我不希望用户配置的静态常量,例如

CONSTANT_URL = “myurl.com”).

public final class Configurations {

private Properties properties = null;

private static Configurations instance = null;

/** Private constructor */

private Configurations (){

this.properties = new Properties();

try{

properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.PATH_CONFFILE));

}catch(Exception ex){

ex.printStackTrace();

}

}

/** Creates the instance is synchronized to avoid multithreads problems */

private synchronized static void createInstance () {

if (instance == null) {

instance = new Configurations ();

}

}

/** Get the properties instance. Uses singleton pattern */

public static Configurations getInstance(){

// Uses singleton pattern to guarantee the creation of only one instance

if(instance == null) {

createInstance();

}

return instance;

}

/** Get a property of the property file */

public String getProperty(String key){

String result = null;

if(key !=null && !key.trim().isEmpty()){

result = this.properties.getProperty(key);

}

return result;

}

/** Override the clone method to ensure the "unique instance" requeriment of this class */

public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}}

Constant类包含对属性和常量的引用.

public class Constants {

// Properties (user configurable)

public static final String DB_URL = "db.url";

public static final String DB_DRIVER = "db.driver";

// Constants (not user configurable)

public static final String PATH_CONFFILE = "config/config.properties";

public static final int MYCONSTANT_ONE = 1;

}

属性文件将是:

db.url=www.myurl.com

db.driver=mysql

要读取属性和常量将是:

// Constants

int i = Constants.MYCONSTANT_ONE;

// Properties

String url = Configurations.getInstance().getProperty(Constants.DB_URL);

你认为这是一个好方法吗?在Java中读取属性和常量的方法是什么?

提前致谢.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值