使用beanFactory工厂实例化容器的方式实现单例模式

//配置文件bean.properties(注意书写顺序)

accountService=com.itheima.service.impl.AccountServiceImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl

 

package com.hope.factory;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
* @author newcityman
* @date 2019/11/18 - 14:44
* 第一个:需要一个配置文件来配置我们的service和dao
* 第二个:通过读取配置文件中配置的内容,反射创建对象
*/
public class BeanFactory {
//定义一个properties对象
public static Properties props;
private static Map<String,Object> beans;
//使用静态代码块为properties对象赋值
static {
try {
//定义一个properties对象
props = new Properties();
//获取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("初始化propteies失败");
}
}

/**
* 根据bean的名称获取bean对象
*
* @param beanName
* @return
*/
public static Object getBean(String beanName) {

return beans.get(beanName);
}
}

package com.hope.ui;

import com.hope.factory.BeanFactory;
import com.hope.service.IAccountService;

/**
* @author newcityman
* @date 2019/11/18 - 14:23
*/
public class Client {

public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
IAccountService as = (IAccountService)BeanFactory.getBean("accountService");
System.out.println(as);
as.findAll();
}
}
 
posted on 2019-11-18 21:51  小猪_佩奇  阅读(1029)  评论(0编辑  收藏  举报