在使用hibernate或者spring的时候,我们往往通过配置文件配置数据库连接属性。但这次项目中并没有用到hibernate和spring,只用到了struts2。要如何实现通过读取文件配置获取属性值呢?ResourceBundle这个类可是实现读取properties文件来获取值
在java中:
public final static Object initLock = new Object();
private final static String DRIVERNAME = "driverName"; //driverName是properties文件中定义的
private final static String URL = "url";
private final static String USER = "user";
private final static String PASSWORD = "password";
private final static String PROPERTIES_FILE_NAME = "property";
private static ResourceBundle bundle = null;
private static String driverName;
private static String url;
private static String user;
private static String password;
static{
try{
if(bundle ==null){
synchronized (initLock) {
if(bundle == null)
bundle = ResourceBundle.getBundle(PROPERTIES_FILE_NAME,Locale.CHINA);
}
}
driverName = bundle.getString(DRIVERNAME).trim();
url = bundle.getString(URL).trim();
user = bundle.getString(USER).trim();
password = bundle.getString(PASSWORD).trim();
}catch(Exception e){
System.out.println("读取资源文件property_zh.properties失败!");
}
}
在.properties文件中:
driverName=com.mysql.jdbc.Driver
url=xxxxx\:3307/9zgame?
user=root
password=xxxxxx
文件名字为:property_zh.properties。后zh根据Locale.CHINA一致的,如果Locale.ENGLISH,则文件名为:property_en.properties