黑马程序员技术交流社区
标题:
工厂 单例 读取配置文件 获取实现类的类名云计算day02
[打印本页]
作者:
tfy
时间:
2012-12-18 00:04
标题:
工厂 单例 读取配置文件 获取实现类的类名云计算day02
package com.itheima.exam.factory;
import java.io.FileInputStream;
import java.util.Properties;
import com.itheima.exam.dao.StudentDao;
public class DaoFactory {
private String studentDaoClassName;
//工厂
//单例
private DaoFactory(){
try {
//读取配置文件 获取实现类的类名
Properties props = new Properties();
props.load(new FileInputStream("src/dao.properties"));
this.studentDaoClassName = props.getProperty("studentDao");
} catch (Exception e) {
// TODO: handle exception
throw new ExceptionInInitializerError();
}
}
private static DaoFactory factory=new DaoFactory();
public static DaoFactory getInstance(){
return factory;
}
//生产dao
public StudentDao newstuStudentDao(){
try {
return (StudentDao) Class.forName(this.studentDaoClassName).newInstance();
} catch (Exception e) {
throw new FactoryException(e);
}
}
}
作者:
邵天强
时间:
2012-12-18 08:29
上面的代码需要有改进的地方,读取配置文件时,最好用类加载器取出,你上面的代码 props.load(new FileInputStream("src/dao.properties"));
发布到tomcat中就没有“src/dao.properties”这个路径,会出错,
String filename=DaoFactory.class.getClassLoader().getResource("properties").getPath();
props.load(new FileInputStream(filename));效果是比较好一点,如果一个配置文件在类路径下面,最好
用类加载器去读取文件,小建议,欢迎指正
作者:
tfy
时间:
2012-12-18 21:04
欢迎交流哦 向你学习啊
作者:
李栋伟
时间:
2012-12-19 09:43
学习~{:soso_e160:}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2