版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40178464/article/details/81639263
为了避免代码的耦合,DAO层使用工厂模式来实现。
1.写一个配置文件daoconfig.properties,这里employee是我自己的一个表
employeeDaoClass=jdbc.dao.EmployeeDaoJdbcImplement
2.DAO接口:定义methods
public interface EmployeeDao {
//methods
}
3.DAO接口的JDBC实现:
public class EmployeeDaoJdbcImplement implements EmployeeDao {
@Override
//methods
}
4.DAO工厂:单例模式实现
class DaoFactory {
private static EmployeeDao employeeDao = null;
private static DaoFactory daoFactory = new DaoFactory();
private DaoFactory() {
try {
Properties prop = new Properties();
// 采用class.getClassLoader().getResourceAsStream()方式读取配置文件
InputStream inStream = DaoFactory.class.getClassLoader()
.getResourceAsStream("daoconfig.properties");
prop.load(inStream);
String employeeDaoClass = prop.getProperty("employeeDaoClass");
// java9中newInstance()方法已过期,使用getDeclaredConstructor().newInstance()代替
employeeDao = (EmployeeDao) Class.forName(employeeDaoClass).newInstance();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
static DaoFactory getDaoFactory() {
return daoFactory;
}
EmployeeDao getEmployeeDao() {
return employeeDao;
}
}
5.利用DAO访问数据层:service层与数据层通过DAO工厂实现连接,没有任何一个new对象,充分降低了代码耦合,提高了可维护性
public class EmployeeDaoTest {
public static void main(String[] args) {
EmployeeDao employeeDao = DaoFactory.getDaoFactory().getEmployeeDao();
//code
employeeDao.methods();
}
}
关于class.getClassLoader().getResourceAsStream()为null的问题:
以上的代码我是用IDEA的maven项目写的,创建的配置文件daoconfig.properties放在了src目录下,结果读取后inStream始终为null,这是因为把配置文件放在src下是普通项目的做法,而maven项目下有一个source目录专门用于存放各种配置文件,将daoconfig.properties文件放入source目录下问题就解决了。