码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-11-18 22:01:11      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:ring   print   实例   stat   weight   string   注意   实例化   失败   

//配置文件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();
}
}
 

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

标签:ring   print   实例   stat   weight   string   注意   实例化   失败   

原文地址:https://www.cnblogs.com/newcityboy/p/11885708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!