简单ioc模拟-使用工厂方法

来源:互联网 发布:spss数据显著性分析 编辑:程序博客网 时间:2024/06/05 08:33
//模拟简单的ioc容器
public class BeanFactory{


private static Properties props = new Properties();
static{
InputStream in = BeanFactory.class.getResourceAsStream("/beans.properties");
try{
props.load(in);
}catch(IOException e){
e.printStackTrace();
}
}
public static Object getBean(String name){
//通过name在properties文件找到类名称
String className = props.getProperty(name);
//通过反射构造类的对象
try{
return Class.forName(className).newInstance();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}


public class ActionDemo{
public static void main(String[] args){
CustomerService customerService = (CustomerService)BeanFactory.getBean("customerService");
customerSerivce.save();
}
}
原创粉丝点击