一般来说一个项目打包之后便不能修改类中属性,但是一些信息有必要多次修改,例如jdbc连接数据库时在DriverManager.getConnection(url, user, password)中的url,user,password经常需要修改,因此我们需要一个配置文件专门配置这些信息。
properties文件是以.properties结尾的配置文件,这种文件以key=value格式存储内容,Java中可以直接使用Properties类来读取这个文件。我们可以将jdbc连接数据库所需要的信息存储在properties文件中。
例如:
url=jdbc:mysql://127.0.0.1:3306/test
user_name=root
password=
如何使用:
public class PropertiesUtil {
private static Properties properties = new Properties();
static {
InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(inputStream);//将properties文件中的每对key=value变为map集合中的键值对
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getValue(String key) {
return properties.getProperty(key);
}
public static void main(String[] args) {
String url = PropertiesUtil.getValue("url");
String user_name = PropertiesUtil.getValue("user_name");
String password = PropertiesUtil.getValue("password");
System.out.println(url+","+user_name+","+password);
}
}
执行结果:
因为此处我的数据库密码为空故输出为空。
而此时获取连接方法变为:
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = PropertiesUtil.getValue("url");
String userName = PropertiesUtil.getValue("user_name");
String password = PropertiesUtil.getValue("password");
return DriverManager.getConnection(url,userName,password);
} catch (Exception e) {
logger.debug(e.getMessage(),e);
}
return null;
}