工厂模式的概念不提了
在使用Properties配置文件时,使用FileInputStream载入配置文件
public class DaoFactory { private ArchiveDao archiveDao; private DaoFactory{ Properties prop = new Properties(); try{ // 导入配置文件 FileInputStream fis = new FileInputStream("src/JdbcUtils/daoconfig.properties"); prop.load(fis); String className = prop.getProperty("archiveDaoClass"); Class<?> clazz = Class.forName(className); archiveDao = (ArchiveDao) clazz.newInstance(); fis.close(); } catch(Throwable e) { throw new ExceptionInInitializerError(e); } } public static DaoFactory getInstace() { return instance; } public ArchiveDao createArchiveDao() { return archiveDao; } }daoconfig.properties 配置文件如下
archiveDaoClass=DaoImpl.ArchiveDaoImpl当我们在对应的Dao的Impl中初始化外界的实例
public class ArchiveDaoImpl implements ArchiveDao { private SpriteService spriteService = new SpriteService(); …… }就会有java.lang.ExceptionInInitializerError的异常问题
Exception in thread "JavaFX Application Thread" java.lang.ExceptionInInitializerError at databaseDao.DaoFactory.<init>(DaoFactory.java:67)解决办法: 只需把实例化的位置放入方法中,不作为静态实例化即可
public class ArchiveDaoImpl implements ArchiveDao { …… // 从数据库中获取用户的所有存档 @Override public Archive[] getArchives(User user) { Connection con = null; PreparedStatement st = null; ResultSet rs = null; try{ con = JdbcUtils.getConnection(); int count = getCount(user); Archive[] archives = new Archive[count]; String sql = "SELECT * FROM archives WHERE userCode = ?"; st = con.prepareStatement(sql); st.setInt(1, user.getCode()); rs = st.executeQuery(); int i = 0; // 方法内部直接实例化 SpriteService spriteService = new SpriteService(); while(rs.next()) { Archive archive = new Archive(rs.getString("name")); archive.setUser(user); Sprite sprite = spriteService.query(rs.getInt("spriteCode")); if(sprite != null) archive.setSprite(sprite); archive.setTaskProgress(rs.getInt("taskProgress")); archives[i] = archive; } return archives; } catch(Exception e) { // 抛出异常 throw new DaoException(e.getMessage(), e); } finally { // 释放内存 JdbcUtils.free(rs, st, con); } } …… }如有缺漏之处或者可以完善的地方,欢迎朋友们参与交流
欢迎各位大大互fo, 这里是YCaptain71