在resources下创建bean.properties

accountService=cn.flypig666.service.impl.AccountServiceImpl
accountDao=cn.flypig666.dao.impl.AccountDaoImpl

创建工厂:BeanFactory.java

创建单例对象效果更好

创建Map<String,Object>类型的容器beans

 //定义一个Properties对象
private static Properties props; //定义一个Map,用于存放我们要创建的对象,称之为容器
private static Map<String,Object> beans; //使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
props = new Properties();
//获取properties文件的流对象,创建在resources文件夹下的properties文件会成为类根路径下的文件,不用写包名
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的 Key
Enumeration keys = props.keys();
//遍历枚举
while (keys.hasMoreElements()){
//取出每个key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = props.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器中
beans.put(key,value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败");
}
} public static Object getBean(String beanName){
return beans.get(beanName);
}
     /**
* 根据Bean的名称获取bean对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
Object bean = null;
try{
String beanPath = props.getProperty(beanName);
System.out.println(beanPath);
bean = Class.forName(beanPath).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return bean;
} }

通过反射获取对象

/**
* 账户业务层实现类
*/
public class AccountServiceImpl implements IAccountService { //private IAccountDao accountDao = new AccountDaoImpl();
private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao"); public void saveAccount(){
accountDao.saveAccount();
}
}
/**
* 模拟一个表现层,用于调用业务层
*/
public class Client { public static void main(String[] args) {
// IAccountService accountService = new AccountServiceImpl();
IAccountService accountService = (IAccountService) BeanFactory.getBean("accountService");
accountService.saveAccount();
}
}

最新文章

  1. HTML 学习笔记 CSS3 (多列)
  2. ruby api 2.1新增改变
  3. CSS3之创建透明边框三角
  4. Jtemplates 基本语法
  5. webx学习笔记
  6. 玩转Android之在线视频播放控件Vitamio的使用
  7. C#利用NPOI生成具有精确列宽行高的Excel文件
  8. ubuntu远程连接
  9. python可变参数调用函数的问题
  10. ios UIKit动力 分类: ios技术 2015-07-14 12:55 196人阅读 评论(0) 收藏
  11. go 语言的序列化与反序列化
  12. 利用toggle实现背包
  13. Django开发目录
  14. 如何使用Shell判断版本号的大小
  15. vue为app做h5页面,如何做到同域名对应不同版本的h5代码
  16. C语言中的地址传递(传指针,传递给形参的指针仍然是实参指针的一份拷贝)
  17. Android源码阅读笔记二 消息处理机制
  18. git openssl 模块生成 https 请求的 ssl 测试证书
  19. pring Boot 与Spring Cloud版本对应
  20. LeetCode 35 Search Insert Position(查找插入位置)

热门文章

  1. NX二次开发-UFUN编辑图层类别描述UF_LAYER_edit_category_descr
  2. Scala 学习2
  3. jenkins深入浅出
  4. HTTP入门简介
  5. 2019-7-27-解决从旧格式的-csproj-迁移到新格式的-csproj-格式-AssemblyInfo-文件值重复问题...
  6. PHP算法之盛最多水的容器
  7. mysql 存储过程学习 汇总
  8. Java 异常基本结构
  9. redis笔记_源码_跳表skiplist
  10. 计算几何——线段和直线判交点poj3304