基於Properties文件的對象工廠工具

 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 {
}

 

發佈了45 篇原創文章 · 獲贊 0 · 訪問量 1459
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章