问题描述:
在WEB应用使用自己编写的jdbcUtils出现NoClassDefFoundError:无法初始化类util . jdbcutils
public class jdbcUtils {
private static Properties properties ;
private static String url;
private static String username;
private static String password;
static {
InputStream is = jdbcUtils.class.getResourceAsStream("db.properties");
properties = new Properties();
try {
Class.forName("com.mysql.jdbc.Driver");
properties.load(is);
password=properties.getProperty("mysql.password");
username=properties.getProperty("mysql.username");
url= properties.getProperty("mysql.url");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
原因分析:
问题出现在properties.load(is);
这句,然后打印了一下is发现为null,终于找到了
解决方案:
在jdbcUtils.class.getResourceAsStream();
方法加载配置文件时应传入"/db.properties"
而不是"db.properties"
还应该注意的是在web项目中无法自动注册驱动,还需要加上Class.forName("com.mysql.jdbc.Driver")