基于Properties文件的对象工厂工具_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 基于Properties文件的对象工厂工具

基于Properties文件的对象工厂工具

 2010/12/25 0:04:36  lichaozhangobj  http://lichaozhangobj.javaeye.com  我要评论(0)
  • 摘要:BeanFactorypackagecom.lichaozhang.util;importjava.io.IOException;importjava.io.InputStream;importjava.util.HashMap;importjava.util.Map;importjava.util.Properties;publicclassBeanFactory{privatestaticMap<String,Object>beanMap=newHashMap<
  • 标签:文件 工具

?BeanFactory

package com.lichaozhang.util;

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

public class BeanFactory {

	private static Map<String, Object> beanMap = new HashMap<String, Object>();

	static {
		// 读取配置文件
		Properties props = loadProperties("beans.properties");

		// 生成所有对象的实例,放到 beanMap 中
		for (Object key : props.keySet()) {
			String name = (String) key;
			String className = props.getProperty(name);
			try {
				// 生成实例
				Object instance = Class.forName(className).newInstance();
				// 放到beanMap中
				beanMap.put(name, instance);
			} catch (Exception e) {
				throw new RuntimeException("初始化实例出错:" + name + " = " + className, e);
			}
		}
	}

	private static Properties loadProperties(String resource) {
		Properties props = new Properties();
		InputStream in = null;
		try {
			in = BeanFactory.class.getClassLoader().getResourceAsStream(resource);
			props.load(in);
		} catch (IOException e) {
			throw new RuntimeException("加载配置文件出错:" + resource, e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return props;
	}

	/**
	 * 获取指定接口对应的实现类
	 * 
	 * @param <T>
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz) {
		return (T) beanMap.get(clazz.getSimpleName());
	}
}

beans.properties

??

StoreDao=com.lichaozhang.dao.impl.StoreDaoImpl

?

StoreService

public interface StoreService {
}

?StoreServiceImpl

public class StoreServiceImpl implements StoreService {

	private StoreDao storeDao = BeanFactory.getBean(StoreDao.class);//BeanFactory用法
}

??StoreDao

public interface StoreDao {
}

?StoreDaoImpl

public class StoreDaoImpl implements StoreDao {
}

?

发表评论
用户名: 匿名