使用BeanFactory工厂对象优化J2EE的传统三层架构中的高耦合现象

BeanFactory类的设置

public class BeanFactory {
	
	
	/**
	 * 解析properties文件,放到map里面
	 */
	static Map<String, String> mapping = new HashMap<>();
	//静态初始化,得到文件流
	static{
		InputStream is = BeanFactory.class.getResourceAsStream("../bean.properties");
		Properties properties = new Properties();
		//把流加载到propertie里面
		try {
			System.out.println(is);
			properties.load(is);
			//遍历properties
			Set<Entry<Object,Object>> entrySet = properties.entrySet();
			for (Entry<Object, Object> entry : entrySet) {
				mapping.put(entry.getKey().toString(), entry.getValue().toString());
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			System.out.println("解析配置文件异常");
		}
	}
	
	/**
	 * 
	 * @param 根据key去创建对象
	 * @return
	 * @SuppressWarnings注解主要用在取消一些编译器产生的警告对代码左侧行列的遮挡
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String key){
		T t = null;	
		try {
			//根据key去mapping中取出完成限定名
			String path = mapping.get(key);
			Class<?> forName = Class.forName(path);
			t =(T) forName.newInstance();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return t;
		
	}
}

将所业务层、web层所需要的类的对象实现与properties文件相对应

这样的话新的功能需求在创建好相对应的类之后只需要把它们对应的实现在bean.properties文件中添加就行啦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值